3 * https://www.mediawiki.org/wiki/OOjs_UI
5 * Copyright 2011–2016 OOjs UI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: 2016-03-08T21:46:49Z
16 * Namespace for all classes, static methods and static properties.
48 * Constants for MouseEvent.which
52 OO
.ui
.MouseButtons
= {
64 * Generate a unique ID for element
66 * @return {string} [id]
68 OO
.ui
.generateElementId = function () {
70 return 'oojsui-' + OO
.ui
.elementId
;
74 * Check if an element is focusable.
75 * Inspired from :focusable in jQueryUI v1.11.4 - 2015-04-14
77 * @param {jQuery} $element Element to test
80 OO
.ui
.isFocusableElement = function ( $element
) {
82 element
= $element
[ 0 ];
84 // Anything disabled is not focusable
85 if ( element
.disabled
) {
89 // Check if the element is visible
91 // This is quicker than calling $element.is( ':visible' )
92 $.expr
.filters
.visible( element
) &&
93 // Check that all parents are visible
94 !$element
.parents().addBack().filter( function () {
95 return $.css( this, 'visibility' ) === 'hidden';
101 // Check if the element is ContentEditable, which is the string 'true'
102 if ( element
.contentEditable
=== 'true' ) {
106 // Anything with a non-negative numeric tabIndex is focusable.
107 // Use .prop to avoid browser bugs
108 if ( $element
.prop( 'tabIndex' ) >= 0 ) {
112 // Some element types are naturally focusable
113 // (indexOf is much faster than regex in Chrome and about the
114 // same in FF: https://jsperf.com/regex-vs-indexof-array2)
115 nodeName
= element
.nodeName
.toLowerCase();
116 if ( [ 'input', 'select', 'textarea', 'button', 'object' ].indexOf( nodeName
) !== -1 ) {
120 // Links and areas are focusable if they have an href
121 if ( ( nodeName
=== 'a' || nodeName
=== 'area' ) && $element
.attr( 'href' ) !== undefined ) {
129 * Find a focusable child
131 * @param {jQuery} $container Container to search in
132 * @param {boolean} [backwards] Search backwards
133 * @return {jQuery} Focusable child, an empty jQuery object if none found
135 OO
.ui
.findFocusable = function ( $container
, backwards
) {
136 var $focusable
= $( [] ),
137 // $focusableCandidates is a superset of things that
138 // could get matched by isFocusableElement
139 $focusableCandidates
= $container
140 .find( 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]' );
143 $focusableCandidates
= Array
.prototype.reverse
.call( $focusableCandidates
);
146 $focusableCandidates
.each( function () {
147 var $this = $( this );
148 if ( OO
.ui
.isFocusableElement( $this ) ) {
157 * Get the user's language and any fallback languages.
159 * These language codes are used to localize user interface elements in the user's language.
161 * In environments that provide a localization system, this function should be overridden to
162 * return the user's language(s). The default implementation returns English (en) only.
164 * @return {string[]} Language codes, in descending order of priority
166 OO
.ui
.getUserLanguages = function () {
171 * Get a value in an object keyed by language code.
173 * @param {Object.<string,Mixed>} obj Object keyed by language code
174 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
175 * @param {string} [fallback] Fallback code, used if no matching language can be found
176 * @return {Mixed} Local value
178 OO
.ui
.getLocalValue = function ( obj
, lang
, fallback
) {
181 // Requested language
185 // Known user language
186 langs
= OO
.ui
.getUserLanguages();
187 for ( i
= 0, len
= langs
.length
; i
< len
; i
++ ) {
194 if ( obj
[ fallback
] ) {
195 return obj
[ fallback
];
197 // First existing language
198 for ( lang
in obj
) {
206 * Check if a node is contained within another node
208 * Similar to jQuery#contains except a list of containers can be supplied
209 * and a boolean argument allows you to include the container in the match list
211 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
212 * @param {HTMLElement} contained Node to find
213 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
214 * @return {boolean} The node is in the list of target nodes
216 OO
.ui
.contains = function ( containers
, contained
, matchContainers
) {
218 if ( !Array
.isArray( containers
) ) {
219 containers
= [ containers
];
221 for ( i
= containers
.length
- 1; i
>= 0; i
-- ) {
222 if ( ( matchContainers
&& contained
=== containers
[ i
] ) || $.contains( containers
[ i
], contained
) ) {
230 * Return a function, that, as long as it continues to be invoked, will not
231 * be triggered. The function will be called after it stops being called for
232 * N milliseconds. If `immediate` is passed, trigger the function on the
233 * leading edge, instead of the trailing.
235 * Ported from: http://underscorejs.org/underscore.js
237 * @param {Function} func
238 * @param {number} wait
239 * @param {boolean} immediate
242 OO
.ui
.debounce = function ( func
, wait
, immediate
) {
247 later = function () {
250 func
.apply( context
, args
);
253 if ( immediate
&& !timeout
) {
254 func
.apply( context
, args
);
256 if ( !timeout
|| wait
) {
257 clearTimeout( timeout
);
258 timeout
= setTimeout( later
, wait
);
264 * Proxy for `node.addEventListener( eventName, handler, true )`.
266 * @param {HTMLElement} node
267 * @param {string} eventName
268 * @param {Function} handler
269 * @deprecated since 0.15.0
271 OO
.ui
.addCaptureEventListener = function ( node
, eventName
, handler
) {
272 node
.addEventListener( eventName
, handler
, true );
276 * Proxy for `node.removeEventListener( eventName, handler, true )`.
278 * @param {HTMLElement} node
279 * @param {string} eventName
280 * @param {Function} handler
281 * @deprecated since 0.15.0
283 OO
.ui
.removeCaptureEventListener = function ( node
, eventName
, handler
) {
284 node
.removeEventListener( eventName
, handler
, true );
288 * Reconstitute a JavaScript object corresponding to a widget created by
289 * the PHP implementation.
291 * This is an alias for `OO.ui.Element.static.infuse()`.
293 * @param {string|HTMLElement|jQuery} idOrNode
294 * A DOM id (if a string) or node for the widget to infuse.
295 * @return {OO.ui.Element}
296 * The `OO.ui.Element` corresponding to this (infusable) document node.
298 OO
.ui
.infuse = function ( idOrNode
) {
299 return OO
.ui
.Element
.static.infuse( idOrNode
);
304 * Message store for the default implementation of OO.ui.msg
306 * Environments that provide a localization system should not use this, but should override
307 * OO.ui.msg altogether.
312 // Tool tip for a button that moves items in a list down one place
313 'ooui-outline-control-move-down': 'Move item down',
314 // Tool tip for a button that moves items in a list up one place
315 'ooui-outline-control-move-up': 'Move item up',
316 // Tool tip for a button that removes items from a list
317 'ooui-outline-control-remove': 'Remove item',
318 // Label for the toolbar group that contains a list of all other available tools
319 'ooui-toolbar-more': 'More',
320 // Label for the fake tool that expands the full list of tools in a toolbar group
321 'ooui-toolgroup-expand': 'More',
322 // Label for the fake tool that collapses the full list of tools in a toolbar group
323 'ooui-toolgroup-collapse': 'Fewer',
324 // Default label for the accept button of a confirmation dialog
325 'ooui-dialog-message-accept': 'OK',
326 // Default label for the reject button of a confirmation dialog
327 'ooui-dialog-message-reject': 'Cancel',
328 // Title for process dialog error description
329 'ooui-dialog-process-error': 'Something went wrong',
330 // Label for process dialog dismiss error button, visible when describing errors
331 'ooui-dialog-process-dismiss': 'Dismiss',
332 // Label for process dialog retry action button, visible when describing only recoverable errors
333 'ooui-dialog-process-retry': 'Try again',
334 // Label for process dialog retry action button, visible when describing only warnings
335 'ooui-dialog-process-continue': 'Continue',
336 // Label for the file selection widget's select file button
337 'ooui-selectfile-button-select': 'Select a file',
338 // Label for the file selection widget if file selection is not supported
339 'ooui-selectfile-not-supported': 'File selection is not supported',
340 // Label for the file selection widget when no file is currently selected
341 'ooui-selectfile-placeholder': 'No file is selected',
342 // Label for the file selection widget's drop target
343 'ooui-selectfile-dragdrop-placeholder': 'Drop file here'
347 * Get a localized message.
349 * In environments that provide a localization system, this function should be overridden to
350 * return the message translated in the user's language. The default implementation always returns
353 * After the message key, message parameters may optionally be passed. In the default implementation,
354 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
355 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
356 * they support unnamed, ordered message parameters.
358 * @param {string} key Message key
359 * @param {...Mixed} [params] Message parameters
360 * @return {string} Translated message with parameters substituted
362 OO
.ui
.msg = function ( key
) {
363 var message
= messages
[ key
],
364 params
= Array
.prototype.slice
.call( arguments
, 1 );
365 if ( typeof message
=== 'string' ) {
366 // Perform $1 substitution
367 message
= message
.replace( /\$(\d+)/g, function ( unused
, n
) {
368 var i
= parseInt( n
, 10 );
369 return params
[ i
- 1 ] !== undefined ? params
[ i
- 1 ] : '$' + n
;
372 // Return placeholder if message not found
373 message
= '[' + key
+ ']';
380 * Package a message and arguments for deferred resolution.
382 * Use this when you are statically specifying a message and the message may not yet be present.
384 * @param {string} key Message key
385 * @param {...Mixed} [params] Message parameters
386 * @return {Function} Function that returns the resolved message when executed
388 OO
.ui
.deferMsg = function () {
389 var args
= arguments
;
391 return OO
.ui
.msg
.apply( OO
.ui
, args
);
398 * If the message is a function it will be executed, otherwise it will pass through directly.
400 * @param {Function|string} msg Deferred message, or message text
401 * @return {string} Resolved message
403 OO
.ui
.resolveMsg = function ( msg
) {
404 if ( $.isFunction( msg
) ) {
411 * @param {string} url
414 OO
.ui
.isSafeUrl = function ( url
) {
415 // Keep this function in sync with php/Tag.php
416 var i
, protocolWhitelist
;
418 function stringStartsWith( haystack
, needle
) {
419 return haystack
.substr( 0, needle
.length
) === needle
;
422 protocolWhitelist
= [
423 'bitcoin', 'ftp', 'ftps', 'geo', 'git', 'gopher', 'http', 'https', 'irc', 'ircs',
424 'magnet', 'mailto', 'mms', 'news', 'nntp', 'redis', 'sftp', 'sip', 'sips', 'sms', 'ssh',
425 'svn', 'tel', 'telnet', 'urn', 'worldwind', 'xmpp'
432 for ( i
= 0; i
< protocolWhitelist
.length
; i
++ ) {
433 if ( stringStartsWith( url
, protocolWhitelist
[ i
] + ':' ) ) {
438 // This matches '//' too
439 if ( stringStartsWith( url
, '/' ) || stringStartsWith( url
, './' ) ) {
442 if ( stringStartsWith( url
, '?' ) || stringStartsWith( url
, '#' ) ) {
454 * Namespace for OOjs UI mixins.
456 * Mixins are named according to the type of object they are intended to
457 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
458 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
459 * is intended to be mixed in to an instance of OO.ui.Widget.
467 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
468 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
469 * connected to them and can't be interacted with.
475 * @param {Object} [config] Configuration options
476 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
477 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
479 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
480 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
481 * @cfg {string} [text] Text to insert
482 * @cfg {Array} [content] An array of content elements to append (after #text).
483 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
484 * Instances of OO.ui.Element will have their $element appended.
485 * @cfg {jQuery} [$content] Content elements to append (after #text).
486 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
487 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
488 * Data can also be specified with the #setData method.
490 OO
.ui
.Element
= function OoUiElement( config
) {
491 // Configuration initialization
492 config
= config
|| {};
497 this.data
= config
.data
;
498 this.$element
= config
.$element
||
499 $( document
.createElement( this.getTagName() ) );
500 this.elementGroup
= null;
501 this.debouncedUpdateThemeClassesHandler
= OO
.ui
.debounce( this.debouncedUpdateThemeClasses
);
504 if ( Array
.isArray( config
.classes
) ) {
505 this.$element
.addClass( config
.classes
.join( ' ' ) );
508 this.$element
.attr( 'id', config
.id
);
511 this.$element
.text( config
.text
);
513 if ( config
.content
) {
514 // The `content` property treats plain strings as text; use an
515 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
516 // appropriate $element appended.
517 this.$element
.append( config
.content
.map( function ( v
) {
518 if ( typeof v
=== 'string' ) {
519 // Escape string so it is properly represented in HTML.
520 return document
.createTextNode( v
);
521 } else if ( v
instanceof OO
.ui
.HtmlSnippet
) {
524 } else if ( v
instanceof OO
.ui
.Element
) {
530 if ( config
.$content
) {
531 // The `$content` property treats plain strings as HTML.
532 this.$element
.append( config
.$content
);
538 OO
.initClass( OO
.ui
.Element
);
540 /* Static Properties */
543 * The name of the HTML tag used by the element.
545 * The static value may be ignored if the #getTagName method is overridden.
551 OO
.ui
.Element
.static.tagName
= 'div';
556 * Reconstitute a JavaScript object corresponding to a widget created
557 * by the PHP implementation.
559 * @param {string|HTMLElement|jQuery} idOrNode
560 * A DOM id (if a string) or node for the widget to infuse.
561 * @return {OO.ui.Element}
562 * The `OO.ui.Element` corresponding to this (infusable) document node.
563 * For `Tag` objects emitted on the HTML side (used occasionally for content)
564 * the value returned is a newly-created Element wrapping around the existing
567 OO
.ui
.Element
.static.infuse = function ( idOrNode
) {
568 var obj
= OO
.ui
.Element
.static.unsafeInfuse( idOrNode
, false );
569 // Verify that the type matches up.
570 // FIXME: uncomment after T89721 is fixed (see T90929)
572 if ( !( obj instanceof this['class'] ) ) {
573 throw new Error( 'Infusion type mismatch!' );
580 * Implementation helper for `infuse`; skips the type check and has an
581 * extra property so that only the top-level invocation touches the DOM.
584 * @param {string|HTMLElement|jQuery} idOrNode
585 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
586 * when the top-level widget of this infusion is inserted into DOM,
587 * replacing the original node; or false for top-level invocation.
588 * @return {OO.ui.Element}
590 OO
.ui
.Element
.static.unsafeInfuse = function ( idOrNode
, domPromise
) {
591 // look for a cached result of a previous infusion.
592 var id
, $elem
, data
, cls
, parts
, parent
, obj
, top
, state
, infusedChildren
;
593 if ( typeof idOrNode
=== 'string' ) {
595 $elem
= $( document
.getElementById( id
) );
597 $elem
= $( idOrNode
);
598 id
= $elem
.attr( 'id' );
600 if ( !$elem
.length
) {
601 throw new Error( 'Widget not found: ' + id
);
603 if ( $elem
[ 0 ].oouiInfused
) {
604 $elem
= $elem
[ 0 ].oouiInfused
;
606 data
= $elem
.data( 'ooui-infused' );
609 if ( data
=== true ) {
610 throw new Error( 'Circular dependency! ' + id
);
613 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
614 state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
615 // restore dynamic state after the new element is re-inserted into DOM under infused parent
616 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
617 infusedChildren
= $elem
.data( 'ooui-infused-children' );
618 if ( infusedChildren
&& infusedChildren
.length
) {
619 infusedChildren
.forEach( function ( data
) {
620 var state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
621 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
627 data
= $elem
.attr( 'data-ooui' );
629 throw new Error( 'No infusion data found: ' + id
);
632 data
= $.parseJSON( data
);
636 if ( !( data
&& data
._
) ) {
637 throw new Error( 'No valid infusion data found: ' + id
);
639 if ( data
._
=== 'Tag' ) {
640 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
641 return new OO
.ui
.Element( { $element
: $elem
} );
643 parts
= data
._
.split( '.' );
644 cls
= OO
.getProp
.apply( OO
, [ window
].concat( parts
) );
645 if ( cls
=== undefined ) {
646 // The PHP output might be old and not including the "OO.ui" prefix
647 // TODO: Remove this back-compat after next major release
648 cls
= OO
.getProp
.apply( OO
, [ OO
.ui
].concat( parts
) );
649 if ( cls
=== undefined ) {
650 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
654 // Verify that we're creating an OO.ui.Element instance
657 while ( parent
!== undefined ) {
658 if ( parent
=== OO
.ui
.Element
) {
663 parent
= parent
.parent
;
666 if ( parent
!== OO
.ui
.Element
) {
667 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
670 if ( domPromise
=== false ) {
672 domPromise
= top
.promise();
674 $elem
.data( 'ooui-infused', true ); // prevent loops
675 data
.id
= id
; // implicit
676 infusedChildren
= [];
677 data
= OO
.copy( data
, null, function deserialize( value
) {
679 if ( OO
.isPlainObject( value
) ) {
681 infused
= OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, domPromise
);
682 infusedChildren
.push( infused
);
683 // Flatten the structure
684 infusedChildren
.push
.apply( infusedChildren
, infused
.$element
.data( 'ooui-infused-children' ) || [] );
685 infused
.$element
.removeData( 'ooui-infused-children' );
689 return new OO
.ui
.HtmlSnippet( value
.html
);
693 // allow widgets to reuse parts of the DOM
694 data
= cls
.static.reusePreInfuseDOM( $elem
[ 0 ], data
);
695 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
696 state
= cls
.static.gatherPreInfuseState( $elem
[ 0 ], data
);
698 // jscs:disable requireCapitalizedConstructors
699 obj
= new cls( data
);
700 // jscs:enable requireCapitalizedConstructors
701 // now replace old DOM with this new DOM.
703 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
704 // so only mutate the DOM if we need to.
705 if ( $elem
[ 0 ] !== obj
.$element
[ 0 ] ) {
706 $elem
.replaceWith( obj
.$element
);
707 // This element is now gone from the DOM, but if anyone is holding a reference to it,
708 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
709 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
710 $elem
[ 0 ].oouiInfused
= obj
.$element
;
714 obj
.$element
.data( 'ooui-infused', obj
);
715 obj
.$element
.data( 'ooui-infused-children', infusedChildren
);
716 // set the 'data-ooui' attribute so we can identify infused widgets
717 obj
.$element
.attr( 'data-ooui', '' );
718 // restore dynamic state after the new element is inserted into DOM
719 domPromise
.done( obj
.restorePreInfuseState
.bind( obj
, state
) );
724 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
726 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
727 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
728 * constructor, which will be given the enhanced config.
731 * @param {HTMLElement} node
732 * @param {Object} config
735 OO
.ui
.Element
.static.reusePreInfuseDOM = function ( node
, config
) {
740 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of a HTML DOM node
741 * (and its children) that represent an Element of the same class and the given configuration,
742 * generated by the PHP implementation.
744 * This method is called just before `node` is detached from the DOM. The return value of this
745 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
746 * is inserted into DOM to replace `node`.
749 * @param {HTMLElement} node
750 * @param {Object} config
753 OO
.ui
.Element
.static.gatherPreInfuseState = function () {
758 * Get a jQuery function within a specific document.
761 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
762 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
764 * @return {Function} Bound jQuery function
766 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
767 function wrapper( selector
) {
768 return $( selector
, wrapper
.context
);
771 wrapper
.context
= this.getDocument( context
);
774 wrapper
.$iframe
= $iframe
;
781 * Get the document of an element.
784 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
785 * @return {HTMLDocument|null} Document object
787 OO
.ui
.Element
.static.getDocument = function ( obj
) {
788 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
789 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
790 // Empty jQuery selections might have a context
797 ( obj
.nodeType
=== 9 && obj
) ||
802 * Get the window of an element or document.
805 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
806 * @return {Window} Window object
808 OO
.ui
.Element
.static.getWindow = function ( obj
) {
809 var doc
= this.getDocument( obj
);
810 return doc
.defaultView
;
814 * Get the direction of an element or document.
817 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
818 * @return {string} Text direction, either 'ltr' or 'rtl'
820 OO
.ui
.Element
.static.getDir = function ( obj
) {
823 if ( obj
instanceof jQuery
) {
826 isDoc
= obj
.nodeType
=== 9;
827 isWin
= obj
.document
!== undefined;
828 if ( isDoc
|| isWin
) {
834 return $( obj
).css( 'direction' );
838 * Get the offset between two frames.
840 * TODO: Make this function not use recursion.
843 * @param {Window} from Window of the child frame
844 * @param {Window} [to=window] Window of the parent frame
845 * @param {Object} [offset] Offset to start with, used internally
846 * @return {Object} Offset object, containing left and top properties
848 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
849 var i
, len
, frames
, frame
, rect
;
855 offset
= { top
: 0, left
: 0 };
857 if ( from.parent
=== from ) {
861 // Get iframe element
862 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
863 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
864 if ( frames
[ i
].contentWindow
=== from ) {
870 // Recursively accumulate offset values
872 rect
= frame
.getBoundingClientRect();
873 offset
.left
+= rect
.left
;
874 offset
.top
+= rect
.top
;
876 this.getFrameOffset( from.parent
, offset
);
883 * Get the offset between two elements.
885 * The two elements may be in a different frame, but in that case the frame $element is in must
886 * be contained in the frame $anchor is in.
889 * @param {jQuery} $element Element whose position to get
890 * @param {jQuery} $anchor Element to get $element's position relative to
891 * @return {Object} Translated position coordinates, containing top and left properties
893 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
894 var iframe
, iframePos
,
895 pos
= $element
.offset(),
896 anchorPos
= $anchor
.offset(),
897 elementDocument
= this.getDocument( $element
),
898 anchorDocument
= this.getDocument( $anchor
);
900 // If $element isn't in the same document as $anchor, traverse up
901 while ( elementDocument
!== anchorDocument
) {
902 iframe
= elementDocument
.defaultView
.frameElement
;
904 throw new Error( '$element frame is not contained in $anchor frame' );
906 iframePos
= $( iframe
).offset();
907 pos
.left
+= iframePos
.left
;
908 pos
.top
+= iframePos
.top
;
909 elementDocument
= iframe
.ownerDocument
;
911 pos
.left
-= anchorPos
.left
;
912 pos
.top
-= anchorPos
.top
;
917 * Get element border sizes.
920 * @param {HTMLElement} el Element to measure
921 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
923 OO
.ui
.Element
.static.getBorders = function ( el
) {
924 var doc
= el
.ownerDocument
,
925 win
= doc
.defaultView
,
926 style
= win
.getComputedStyle( el
, null ),
928 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
929 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
930 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
931 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
942 * Get dimensions of an element or window.
945 * @param {HTMLElement|Window} el Element to measure
946 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
948 OO
.ui
.Element
.static.getDimensions = function ( el
) {
950 doc
= el
.ownerDocument
|| el
.document
,
951 win
= doc
.defaultView
;
953 if ( win
=== el
|| el
=== doc
.documentElement
) {
956 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
958 top
: $win
.scrollTop(),
959 left
: $win
.scrollLeft()
961 scrollbar
: { right
: 0, bottom
: 0 },
965 bottom
: $win
.innerHeight(),
966 right
: $win
.innerWidth()
972 borders
: this.getBorders( el
),
974 top
: $el
.scrollTop(),
975 left
: $el
.scrollLeft()
978 right
: $el
.innerWidth() - el
.clientWidth
,
979 bottom
: $el
.innerHeight() - el
.clientHeight
981 rect
: el
.getBoundingClientRect()
987 * Get scrollable object parent
989 * documentElement can't be used to get or set the scrollTop
990 * property on Blink. Changing and testing its value lets us
991 * use 'body' or 'documentElement' based on what is working.
993 * https://code.google.com/p/chromium/issues/detail?id=303131
996 * @param {HTMLElement} el Element to find scrollable parent for
997 * @return {HTMLElement} Scrollable parent
999 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1000 var scrollTop
, body
;
1002 if ( OO
.ui
.scrollableElement
=== undefined ) {
1003 body
= el
.ownerDocument
.body
;
1004 scrollTop
= body
.scrollTop
;
1007 if ( body
.scrollTop
=== 1 ) {
1008 body
.scrollTop
= scrollTop
;
1009 OO
.ui
.scrollableElement
= 'body';
1011 OO
.ui
.scrollableElement
= 'documentElement';
1015 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1019 * Get closest scrollable container.
1021 * Traverses up until either a scrollable element or the root is reached, in which case the window
1025 * @param {HTMLElement} el Element to find scrollable container for
1026 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1027 * @return {HTMLElement} Closest scrollable container
1029 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1031 // props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
1032 props
= [ 'overflow-x', 'overflow-y' ],
1033 $parent
= $( el
).parent();
1035 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1036 props
= [ 'overflow-' + dimension
];
1039 while ( $parent
.length
) {
1040 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1041 return $parent
[ 0 ];
1045 val
= $parent
.css( props
[ i
] );
1046 if ( val
=== 'auto' || val
=== 'scroll' ) {
1047 return $parent
[ 0 ];
1050 $parent
= $parent
.parent();
1052 return this.getDocument( el
).body
;
1056 * Scroll element into view.
1059 * @param {HTMLElement} el Element to scroll into view
1060 * @param {Object} [config] Configuration options
1061 * @param {string} [config.duration='fast'] jQuery animation duration value
1062 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1063 * to scroll in both directions
1064 * @param {Function} [config.complete] Function to call when scrolling completes.
1065 * Deprecated since 0.15.4, use the return promise instead.
1066 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1068 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1069 var position
, animations
, callback
, container
, $container
, elementDimensions
, containerDimensions
, $window
,
1070 deferred
= $.Deferred();
1072 // Configuration initialization
1073 config
= config
|| {};
1076 callback
= typeof config
.complete
=== 'function' && config
.complete
;
1077 container
= this.getClosestScrollableContainer( el
, config
.direction
);
1078 $container
= $( container
);
1079 elementDimensions
= this.getDimensions( el
);
1080 containerDimensions
= this.getDimensions( container
);
1081 $window
= $( this.getWindow( el
) );
1083 // Compute the element's position relative to the container
1084 if ( $container
.is( 'html, body' ) ) {
1085 // If the scrollable container is the root, this is easy
1087 top
: elementDimensions
.rect
.top
,
1088 bottom
: $window
.innerHeight() - elementDimensions
.rect
.bottom
,
1089 left
: elementDimensions
.rect
.left
,
1090 right
: $window
.innerWidth() - elementDimensions
.rect
.right
1093 // Otherwise, we have to subtract el's coordinates from container's coordinates
1095 top
: elementDimensions
.rect
.top
- ( containerDimensions
.rect
.top
+ containerDimensions
.borders
.top
),
1096 bottom
: containerDimensions
.rect
.bottom
- containerDimensions
.borders
.bottom
- containerDimensions
.scrollbar
.bottom
- elementDimensions
.rect
.bottom
,
1097 left
: elementDimensions
.rect
.left
- ( containerDimensions
.rect
.left
+ containerDimensions
.borders
.left
),
1098 right
: containerDimensions
.rect
.right
- containerDimensions
.borders
.right
- containerDimensions
.scrollbar
.right
- elementDimensions
.rect
.right
1102 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1103 if ( position
.top
< 0 ) {
1104 animations
.scrollTop
= containerDimensions
.scroll
.top
+ position
.top
;
1105 } else if ( position
.top
> 0 && position
.bottom
< 0 ) {
1106 animations
.scrollTop
= containerDimensions
.scroll
.top
+ Math
.min( position
.top
, -position
.bottom
);
1109 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1110 if ( position
.left
< 0 ) {
1111 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ position
.left
;
1112 } else if ( position
.left
> 0 && position
.right
< 0 ) {
1113 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ Math
.min( position
.left
, -position
.right
);
1116 if ( !$.isEmptyObject( animations
) ) {
1117 $container
.stop( true ).animate( animations
, config
.duration
=== undefined ? 'fast' : config
.duration
);
1118 $container
.queue( function ( next
) {
1131 return deferred
.promise();
1135 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1136 * and reserve space for them, because it probably doesn't.
1138 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1139 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1140 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1141 * and then reattach (or show) them back.
1144 * @param {HTMLElement} el Element to reconsider the scrollbars on
1146 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1147 var i
, len
, scrollLeft
, scrollTop
, nodes
= [];
1148 // Save scroll position
1149 scrollLeft
= el
.scrollLeft
;
1150 scrollTop
= el
.scrollTop
;
1151 // Detach all children
1152 while ( el
.firstChild
) {
1153 nodes
.push( el
.firstChild
);
1154 el
.removeChild( el
.firstChild
);
1157 void el
.offsetHeight
;
1158 // Reattach all children
1159 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1160 el
.appendChild( nodes
[ i
] );
1162 // Restore scroll position (no-op if scrollbars disappeared)
1163 el
.scrollLeft
= scrollLeft
;
1164 el
.scrollTop
= scrollTop
;
1170 * Toggle visibility of an element.
1172 * @param {boolean} [show] Make element visible, omit to toggle visibility
1176 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1177 show
= show
=== undefined ? !this.visible
: !!show
;
1179 if ( show
!== this.isVisible() ) {
1180 this.visible
= show
;
1181 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1182 this.emit( 'toggle', show
);
1189 * Check if element is visible.
1191 * @return {boolean} element is visible
1193 OO
.ui
.Element
.prototype.isVisible = function () {
1194 return this.visible
;
1200 * @return {Mixed} Element data
1202 OO
.ui
.Element
.prototype.getData = function () {
1209 * @param {Mixed} data Element data
1212 OO
.ui
.Element
.prototype.setData = function ( data
) {
1218 * Check if element supports one or more methods.
1220 * @param {string|string[]} methods Method or list of methods to check
1221 * @return {boolean} All methods are supported
1223 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1227 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1228 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1229 if ( $.isFunction( this[ methods
[ i
] ] ) ) {
1234 return methods
.length
=== support
;
1238 * Update the theme-provided classes.
1240 * @localdoc This is called in element mixins and widget classes any time state changes.
1241 * Updating is debounced, minimizing overhead of changing multiple attributes and
1242 * guaranteeing that theme updates do not occur within an element's constructor
1244 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1245 this.debouncedUpdateThemeClassesHandler();
1250 * @localdoc This method is called directly from the QUnit tests instead of #updateThemeClasses, to
1251 * make them synchronous.
1253 OO
.ui
.Element
.prototype.debouncedUpdateThemeClasses = function () {
1254 OO
.ui
.theme
.updateElementClasses( this );
1258 * Get the HTML tag name.
1260 * Override this method to base the result on instance information.
1262 * @return {string} HTML tag name
1264 OO
.ui
.Element
.prototype.getTagName = function () {
1265 return this.constructor.static.tagName
;
1269 * Check if the element is attached to the DOM
1271 * @return {boolean} The element is attached to the DOM
1273 OO
.ui
.Element
.prototype.isElementAttached = function () {
1274 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1278 * Get the DOM document.
1280 * @return {HTMLDocument} Document object
1282 OO
.ui
.Element
.prototype.getElementDocument = function () {
1283 // Don't cache this in other ways either because subclasses could can change this.$element
1284 return OO
.ui
.Element
.static.getDocument( this.$element
);
1288 * Get the DOM window.
1290 * @return {Window} Window object
1292 OO
.ui
.Element
.prototype.getElementWindow = function () {
1293 return OO
.ui
.Element
.static.getWindow( this.$element
);
1297 * Get closest scrollable container.
1299 * @return {HTMLElement} Closest scrollable container
1301 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1302 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1306 * Get group element is in.
1308 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1310 OO
.ui
.Element
.prototype.getElementGroup = function () {
1311 return this.elementGroup
;
1315 * Set group element is in.
1317 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1320 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1321 this.elementGroup
= group
;
1326 * Scroll element into view.
1328 * @param {Object} [config] Configuration options
1329 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1331 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1332 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1336 * Restore the pre-infusion dynamic state for this widget.
1338 * This method is called after #$element has been inserted into DOM. The parameter is the return
1339 * value of #gatherPreInfuseState.
1342 * @param {Object} state
1344 OO
.ui
.Element
.prototype.restorePreInfuseState = function () {
1348 * Wraps an HTML snippet for use with configuration values which default
1349 * to strings. This bypasses the default html-escaping done to string
1355 * @param {string} [content] HTML content
1357 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
1359 this.content
= content
;
1364 OO
.initClass( OO
.ui
.HtmlSnippet
);
1371 * @return {string} Unchanged HTML snippet.
1373 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
1374 return this.content
;
1378 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1379 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1380 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1381 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1382 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1386 * @extends OO.ui.Element
1387 * @mixins OO.EventEmitter
1390 * @param {Object} [config] Configuration options
1392 OO
.ui
.Layout
= function OoUiLayout( config
) {
1393 // Configuration initialization
1394 config
= config
|| {};
1396 // Parent constructor
1397 OO
.ui
.Layout
.parent
.call( this, config
);
1399 // Mixin constructors
1400 OO
.EventEmitter
.call( this );
1403 this.$element
.addClass( 'oo-ui-layout' );
1408 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1409 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1412 * Widgets are compositions of one or more OOjs UI elements that users can both view
1413 * and interact with. All widgets can be configured and modified via a standard API,
1414 * and their state can change dynamically according to a model.
1418 * @extends OO.ui.Element
1419 * @mixins OO.EventEmitter
1422 * @param {Object} [config] Configuration options
1423 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1424 * appearance reflects this state.
1426 OO
.ui
.Widget
= function OoUiWidget( config
) {
1427 // Initialize config
1428 config
= $.extend( { disabled
: false }, config
);
1430 // Parent constructor
1431 OO
.ui
.Widget
.parent
.call( this, config
);
1433 // Mixin constructors
1434 OO
.EventEmitter
.call( this );
1437 this.disabled
= null;
1438 this.wasDisabled
= null;
1441 this.$element
.addClass( 'oo-ui-widget' );
1442 this.setDisabled( !!config
.disabled
);
1447 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1448 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1450 /* Static Properties */
1453 * Whether this widget will behave reasonably when wrapped in a HTML `<label>`. If this is true,
1454 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
1459 * @property {boolean}
1461 OO
.ui
.Widget
.static.supportsSimpleLabel
= false;
1468 * A 'disable' event is emitted when the disabled state of the widget changes
1469 * (i.e. on disable **and** enable).
1471 * @param {boolean} disabled Widget is disabled
1477 * A 'toggle' event is emitted when the visibility of the widget changes.
1479 * @param {boolean} visible Widget is visible
1485 * Check if the widget is disabled.
1487 * @return {boolean} Widget is disabled
1489 OO
.ui
.Widget
.prototype.isDisabled = function () {
1490 return this.disabled
;
1494 * Set the 'disabled' state of the widget.
1496 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1498 * @param {boolean} disabled Disable widget
1501 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
1504 this.disabled
= !!disabled
;
1505 isDisabled
= this.isDisabled();
1506 if ( isDisabled
!== this.wasDisabled
) {
1507 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
1508 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
1509 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
1510 this.emit( 'disable', isDisabled
);
1511 this.updateThemeClasses();
1513 this.wasDisabled
= isDisabled
;
1519 * Update the disabled state, in case of changes in parent widget.
1523 OO
.ui
.Widget
.prototype.updateDisabled = function () {
1524 this.setDisabled( this.disabled
);
1535 * @param {Object} [config] Configuration options
1537 OO
.ui
.Theme
= function OoUiTheme( config
) {
1538 // Configuration initialization
1539 config
= config
|| {};
1544 OO
.initClass( OO
.ui
.Theme
);
1549 * Get a list of classes to be applied to a widget.
1551 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
1552 * otherwise state transitions will not work properly.
1554 * @param {OO.ui.Element} element Element for which to get classes
1555 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1557 OO
.ui
.Theme
.prototype.getElementClasses = function () {
1558 return { on
: [], off
: [] };
1562 * Update CSS classes provided by the theme.
1564 * For elements with theme logic hooks, this should be called any time there's a state change.
1566 * @param {OO.ui.Element} element Element for which to update classes
1567 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1569 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
1570 var $elements
= $( [] ),
1571 classes
= this.getElementClasses( element
);
1573 if ( element
.$icon
) {
1574 $elements
= $elements
.add( element
.$icon
);
1576 if ( element
.$indicator
) {
1577 $elements
= $elements
.add( element
.$indicator
);
1581 .removeClass( classes
.off
.join( ' ' ) )
1582 .addClass( classes
.on
.join( ' ' ) );
1586 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
1587 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
1588 * order in which users will navigate through the focusable elements via the "tab" key.
1591 * // TabIndexedElement is mixed into the ButtonWidget class
1592 * // to provide a tabIndex property.
1593 * var button1 = new OO.ui.ButtonWidget( {
1597 * var button2 = new OO.ui.ButtonWidget( {
1601 * var button3 = new OO.ui.ButtonWidget( {
1605 * var button4 = new OO.ui.ButtonWidget( {
1609 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
1615 * @param {Object} [config] Configuration options
1616 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
1617 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
1618 * functionality will be applied to it instead.
1619 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
1620 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
1621 * to remove the element from the tab-navigation flow.
1623 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
1624 // Configuration initialization
1625 config
= $.extend( { tabIndex
: 0 }, config
);
1628 this.$tabIndexed
= null;
1629 this.tabIndex
= null;
1632 this.connect( this, { disable
: 'onTabIndexedElementDisable' } );
1635 this.setTabIndex( config
.tabIndex
);
1636 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
1641 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
1646 * Set the element that should use the tabindex functionality.
1648 * This method is used to retarget a tabindex mixin so that its functionality applies
1649 * to the specified element. If an element is currently using the functionality, the mixin’s
1650 * effect on that element is removed before the new element is set up.
1652 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
1655 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
1656 var tabIndex
= this.tabIndex
;
1657 // Remove attributes from old $tabIndexed
1658 this.setTabIndex( null );
1659 // Force update of new $tabIndexed
1660 this.$tabIndexed
= $tabIndexed
;
1661 this.tabIndex
= tabIndex
;
1662 return this.updateTabIndex();
1666 * Set the value of the tabindex.
1668 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
1671 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
1672 tabIndex
= typeof tabIndex
=== 'number' ? tabIndex
: null;
1674 if ( this.tabIndex
!== tabIndex
) {
1675 this.tabIndex
= tabIndex
;
1676 this.updateTabIndex();
1683 * Update the `tabindex` attribute, in case of changes to tab index or
1689 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
1690 if ( this.$tabIndexed
) {
1691 if ( this.tabIndex
!== null ) {
1692 // Do not index over disabled elements
1693 this.$tabIndexed
.attr( {
1694 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
1695 // Support: ChromeVox and NVDA
1696 // These do not seem to inherit aria-disabled from parent elements
1697 'aria-disabled': this.isDisabled().toString()
1700 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
1707 * Handle disable events.
1710 * @param {boolean} disabled Element is disabled
1712 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
1713 this.updateTabIndex();
1717 * Get the value of the tabindex.
1719 * @return {number|null} Tabindex value
1721 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
1722 return this.tabIndex
;
1726 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
1727 * interface element that can be configured with access keys for accessibility.
1728 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
1730 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
1736 * @param {Object} [config] Configuration options
1737 * @cfg {jQuery} [$button] The button element created by the class.
1738 * If this configuration is omitted, the button element will use a generated `<a>`.
1739 * @cfg {boolean} [framed=true] Render the button with a frame
1741 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
1742 // Configuration initialization
1743 config
= config
|| {};
1746 this.$button
= null;
1748 this.active
= false;
1749 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
1750 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
1751 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
1752 this.onKeyUpHandler
= this.onKeyUp
.bind( this );
1753 this.onClickHandler
= this.onClick
.bind( this );
1754 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
1757 this.$element
.addClass( 'oo-ui-buttonElement' );
1758 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
1759 this.setButtonElement( config
.$button
|| $( '<a>' ) );
1764 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
1766 /* Static Properties */
1769 * Cancel mouse down events.
1771 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
1772 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
1773 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
1778 * @property {boolean}
1780 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
1785 * A 'click' event is emitted when the button element is clicked.
1793 * Set the button element.
1795 * This method is used to retarget a button mixin so that its functionality applies to
1796 * the specified button element instead of the one created by the class. If a button element
1797 * is already set, the method will remove the mixin’s effect on that element.
1799 * @param {jQuery} $button Element to use as button
1801 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
1802 if ( this.$button
) {
1804 .removeClass( 'oo-ui-buttonElement-button' )
1805 .removeAttr( 'role accesskey' )
1807 mousedown
: this.onMouseDownHandler
,
1808 keydown
: this.onKeyDownHandler
,
1809 click
: this.onClickHandler
,
1810 keypress
: this.onKeyPressHandler
1814 this.$button
= $button
1815 .addClass( 'oo-ui-buttonElement-button' )
1816 .attr( { role
: 'button' } )
1818 mousedown
: this.onMouseDownHandler
,
1819 keydown
: this.onKeyDownHandler
,
1820 click
: this.onClickHandler
,
1821 keypress
: this.onKeyPressHandler
1826 * Handles mouse down events.
1829 * @param {jQuery.Event} e Mouse down event
1831 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
1832 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
1835 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
1836 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
1837 // reliably remove the pressed class
1838 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
1839 // Prevent change of focus unless specifically configured otherwise
1840 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
1846 * Handles mouse up events.
1849 * @param {MouseEvent} e Mouse up event
1851 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp = function ( e
) {
1852 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
1855 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
1856 // Stop listening for mouseup, since we only needed this once
1857 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
1861 * Handles mouse click events.
1864 * @param {jQuery.Event} e Mouse click event
1867 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
1868 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
1869 if ( this.emit( 'click' ) ) {
1876 * Handles key down events.
1879 * @param {jQuery.Event} e Key down event
1881 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
1882 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
1885 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
1886 // Run the keyup handler no matter where the key is when the button is let go, so we can
1887 // reliably remove the pressed class
1888 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler
, true );
1892 * Handles key up events.
1895 * @param {KeyboardEvent} e Key up event
1897 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyUp = function ( e
) {
1898 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
1901 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
1902 // Stop listening for keyup, since we only needed this once
1903 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler
, true );
1907 * Handles key press events.
1910 * @param {jQuery.Event} e Key press event
1913 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
1914 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
1915 if ( this.emit( 'click' ) ) {
1922 * Check if button has a frame.
1924 * @return {boolean} Button is framed
1926 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
1931 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
1933 * @param {boolean} [framed] Make button framed, omit to toggle
1936 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
1937 framed
= framed
=== undefined ? !this.framed
: !!framed
;
1938 if ( framed
!== this.framed
) {
1939 this.framed
= framed
;
1941 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
1942 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
1943 this.updateThemeClasses();
1950 * Set the button's active state.
1952 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
1953 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
1954 * for other button types.
1956 * @param {boolean} value Make button active
1959 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
1960 this.active
= !!value
;
1961 this.$element
.toggleClass( 'oo-ui-buttonElement-active', this.active
);
1966 * Check if the button is active
1968 * @return {boolean} The button is active
1970 OO
.ui
.mixin
.ButtonElement
.prototype.isActive = function () {
1975 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
1976 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
1977 * items from the group is done through the interface the class provides.
1978 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
1980 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
1986 * @param {Object} [config] Configuration options
1987 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
1988 * is omitted, the group element will use a generated `<div>`.
1990 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
1991 // Configuration initialization
1992 config
= config
|| {};
1997 this.aggregateItemEvents
= {};
2000 this.setGroupElement( config
.$group
|| $( '<div>' ) );
2006 * Set the group element.
2008 * If an element is already set, items will be moved to the new element.
2010 * @param {jQuery} $group Element to use as group
2012 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
2015 this.$group
= $group
;
2016 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2017 this.$group
.append( this.items
[ i
].$element
);
2022 * Check if a group contains no items.
2024 * @return {boolean} Group is empty
2026 OO
.ui
.mixin
.GroupElement
.prototype.isEmpty = function () {
2027 return !this.items
.length
;
2031 * Get all items in the group.
2033 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
2034 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
2037 * @return {OO.ui.Element[]} An array of items.
2039 OO
.ui
.mixin
.GroupElement
.prototype.getItems = function () {
2040 return this.items
.slice( 0 );
2044 * Get an item by its data.
2046 * Only the first item with matching data will be returned. To return all matching items,
2047 * use the #getItemsFromData method.
2049 * @param {Object} data Item data to search for
2050 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2052 OO
.ui
.mixin
.GroupElement
.prototype.getItemFromData = function ( data
) {
2054 hash
= OO
.getHash( data
);
2056 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2057 item
= this.items
[ i
];
2058 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2067 * Get items by their data.
2069 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
2071 * @param {Object} data Item data to search for
2072 * @return {OO.ui.Element[]} Items with equivalent data
2074 OO
.ui
.mixin
.GroupElement
.prototype.getItemsFromData = function ( data
) {
2076 hash
= OO
.getHash( data
),
2079 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2080 item
= this.items
[ i
];
2081 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2090 * Aggregate the events emitted by the group.
2092 * When events are aggregated, the group will listen to all contained items for the event,
2093 * and then emit the event under a new name. The new event will contain an additional leading
2094 * parameter containing the item that emitted the original event. Other arguments emitted from
2095 * the original event are passed through.
2097 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
2098 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
2099 * A `null` value will remove aggregated events.
2101 * @throws {Error} An error is thrown if aggregation already exists.
2103 OO
.ui
.mixin
.GroupElement
.prototype.aggregate = function ( events
) {
2104 var i
, len
, item
, add
, remove
, itemEvent
, groupEvent
;
2106 for ( itemEvent
in events
) {
2107 groupEvent
= events
[ itemEvent
];
2109 // Remove existing aggregated event
2110 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
2111 // Don't allow duplicate aggregations
2113 throw new Error( 'Duplicate item event aggregation for ' + itemEvent
);
2115 // Remove event aggregation from existing items
2116 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2117 item
= this.items
[ i
];
2118 if ( item
.connect
&& item
.disconnect
) {
2120 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
2121 item
.disconnect( this, remove
);
2124 // Prevent future items from aggregating event
2125 delete this.aggregateItemEvents
[ itemEvent
];
2128 // Add new aggregate event
2130 // Make future items aggregate event
2131 this.aggregateItemEvents
[ itemEvent
] = groupEvent
;
2132 // Add event aggregation to existing items
2133 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2134 item
= this.items
[ i
];
2135 if ( item
.connect
&& item
.disconnect
) {
2137 add
[ itemEvent
] = [ 'emit', groupEvent
, item
];
2138 item
.connect( this, add
);
2146 * Add items to the group.
2148 * Items will be added to the end of the group array unless the optional `index` parameter specifies
2149 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
2151 * @param {OO.ui.Element[]} items An array of items to add to the group
2152 * @param {number} [index] Index of the insertion point
2155 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
2156 var i
, len
, item
, event
, events
, currentIndex
,
2159 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
2162 // Check if item exists then remove it first, effectively "moving" it
2163 currentIndex
= this.items
.indexOf( item
);
2164 if ( currentIndex
>= 0 ) {
2165 this.removeItems( [ item
] );
2166 // Adjust index to compensate for removal
2167 if ( currentIndex
< index
) {
2172 if ( item
.connect
&& item
.disconnect
&& !$.isEmptyObject( this.aggregateItemEvents
) ) {
2174 for ( event
in this.aggregateItemEvents
) {
2175 events
[ event
] = [ 'emit', this.aggregateItemEvents
[ event
], item
];
2177 item
.connect( this, events
);
2179 item
.setElementGroup( this );
2180 itemElements
.push( item
.$element
.get( 0 ) );
2183 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
2184 this.$group
.append( itemElements
);
2185 this.items
.push
.apply( this.items
, items
);
2186 } else if ( index
=== 0 ) {
2187 this.$group
.prepend( itemElements
);
2188 this.items
.unshift
.apply( this.items
, items
);
2190 this.items
[ index
].$element
.before( itemElements
);
2191 this.items
.splice
.apply( this.items
, [ index
, 0 ].concat( items
) );
2198 * Remove the specified items from a group.
2200 * Removed items are detached (not removed) from the DOM so that they may be reused.
2201 * To remove all items from a group, you may wish to use the #clearItems method instead.
2203 * @param {OO.ui.Element[]} items An array of items to remove
2206 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
2207 var i
, len
, item
, index
, remove
, itemEvent
;
2209 // Remove specific items
2210 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
2212 index
= this.items
.indexOf( item
);
2213 if ( index
!== -1 ) {
2215 item
.connect
&& item
.disconnect
&&
2216 !$.isEmptyObject( this.aggregateItemEvents
)
2219 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
2220 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
2222 item
.disconnect( this, remove
);
2224 item
.setElementGroup( null );
2225 this.items
.splice( index
, 1 );
2226 item
.$element
.detach();
2234 * Clear all items from the group.
2236 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2237 * To remove only a subset of items from a group, use the #removeItems method.
2241 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
2242 var i
, len
, item
, remove
, itemEvent
;
2245 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2246 item
= this.items
[ i
];
2248 item
.connect
&& item
.disconnect
&&
2249 !$.isEmptyObject( this.aggregateItemEvents
)
2252 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
2253 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
2255 item
.disconnect( this, remove
);
2257 item
.setElementGroup( null );
2258 item
.$element
.detach();
2266 * IconElement is often mixed into other classes to generate an icon.
2267 * Icons are graphics, about the size of normal text. They are used to aid the user
2268 * in locating a control or to convey information in a space-efficient way. See the
2269 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
2270 * included in the library.
2272 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2278 * @param {Object} [config] Configuration options
2279 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2280 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2281 * the icon element be set to an existing icon instead of the one generated by this class, set a
2282 * value using a jQuery selection. For example:
2284 * // Use a <div> tag instead of a <span>
2286 * // Use an existing icon element instead of the one generated by the class
2287 * $icon: this.$element
2288 * // Use an icon element from a child widget
2289 * $icon: this.childwidget.$element
2290 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
2291 * symbolic names. A map is used for i18n purposes and contains a `default` icon
2292 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
2293 * by the user's language.
2295 * Example of an i18n map:
2297 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2298 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
2299 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2300 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
2301 * text. The icon title is displayed when users move the mouse over the icon.
2303 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
2304 // Configuration initialization
2305 config
= config
|| {};
2310 this.iconTitle
= null;
2313 this.setIcon( config
.icon
|| this.constructor.static.icon
);
2314 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
2315 this.setIconElement( config
.$icon
|| $( '<span>' ) );
2320 OO
.initClass( OO
.ui
.mixin
.IconElement
);
2322 /* Static Properties */
2325 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
2326 * for i18n purposes and contains a `default` icon name and additional names keyed by
2327 * language code. The `default` name is used when no icon is keyed by the user's language.
2329 * Example of an i18n map:
2331 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2333 * Note: the static property will be overridden if the #icon configuration is used.
2337 * @property {Object|string}
2339 OO
.ui
.mixin
.IconElement
.static.icon
= null;
2342 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2343 * function that returns title text, or `null` for no title.
2345 * The static property will be overridden if the #iconTitle configuration is used.
2349 * @property {string|Function|null}
2351 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
2356 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2357 * applies to the specified icon element instead of the one created by the class. If an icon
2358 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2359 * and mixin methods will no longer affect the element.
2361 * @param {jQuery} $icon Element to use as icon
2363 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
2366 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
2367 .removeAttr( 'title' );
2371 .addClass( 'oo-ui-iconElement-icon' )
2372 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
2373 if ( this.iconTitle
!== null ) {
2374 this.$icon
.attr( 'title', this.iconTitle
);
2377 this.updateThemeClasses();
2381 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
2382 * The icon parameter can also be set to a map of icon names. See the #icon config setting
2385 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
2386 * by language code, or `null` to remove the icon.
2389 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
2390 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
2391 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
2393 if ( this.icon
!== icon
) {
2395 if ( this.icon
!== null ) {
2396 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
2398 if ( icon
!== null ) {
2399 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
2405 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
2406 this.updateThemeClasses();
2412 * Set the icon title. Use `null` to remove the title.
2414 * @param {string|Function|null} iconTitle A text string used as the icon title,
2415 * a function that returns title text, or `null` for no title.
2418 OO
.ui
.mixin
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
2419 iconTitle
= typeof iconTitle
=== 'function' ||
2420 ( typeof iconTitle
=== 'string' && iconTitle
.length
) ?
2421 OO
.ui
.resolveMsg( iconTitle
) : null;
2423 if ( this.iconTitle
!== iconTitle
) {
2424 this.iconTitle
= iconTitle
;
2426 if ( this.iconTitle
!== null ) {
2427 this.$icon
.attr( 'title', iconTitle
);
2429 this.$icon
.removeAttr( 'title' );
2438 * Get the symbolic name of the icon.
2440 * @return {string} Icon name
2442 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
2447 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
2449 * @return {string} Icon title text
2451 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
2452 return this.iconTitle
;
2456 * IndicatorElement is often mixed into other classes to generate an indicator.
2457 * Indicators are small graphics that are generally used in two ways:
2459 * - To draw attention to the status of an item. For example, an indicator might be
2460 * used to show that an item in a list has errors that need to be resolved.
2461 * - To clarify the function of a control that acts in an exceptional way (a button
2462 * that opens a menu instead of performing an action directly, for example).
2464 * For a list of indicators included in the library, please see the
2465 * [OOjs UI documentation on MediaWiki] [1].
2467 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2473 * @param {Object} [config] Configuration options
2474 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
2475 * configuration is omitted, the indicator element will use a generated `<span>`.
2476 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2477 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
2479 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2480 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
2481 * or a function that returns title text. The indicator title is displayed when users move
2482 * the mouse over the indicator.
2484 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
2485 // Configuration initialization
2486 config
= config
|| {};
2489 this.$indicator
= null;
2490 this.indicator
= null;
2491 this.indicatorTitle
= null;
2494 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
2495 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
2496 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
2501 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
2503 /* Static Properties */
2506 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2507 * The static property will be overridden if the #indicator configuration is used.
2511 * @property {string|null}
2513 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
2516 * A text string used as the indicator title, a function that returns title text, or `null`
2517 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
2521 * @property {string|Function|null}
2523 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
2528 * Set the indicator element.
2530 * If an element is already set, it will be cleaned up before setting up the new element.
2532 * @param {jQuery} $indicator Element to use as indicator
2534 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
2535 if ( this.$indicator
) {
2537 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
2538 .removeAttr( 'title' );
2541 this.$indicator
= $indicator
2542 .addClass( 'oo-ui-indicatorElement-indicator' )
2543 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
2544 if ( this.indicatorTitle
!== null ) {
2545 this.$indicator
.attr( 'title', this.indicatorTitle
);
2548 this.updateThemeClasses();
2552 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
2554 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
2557 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
2558 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
2560 if ( this.indicator
!== indicator
) {
2561 if ( this.$indicator
) {
2562 if ( this.indicator
!== null ) {
2563 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
2565 if ( indicator
!== null ) {
2566 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
2569 this.indicator
= indicator
;
2572 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
2573 this.updateThemeClasses();
2579 * Set the indicator title.
2581 * The title is displayed when a user moves the mouse over the indicator.
2583 * @param {string|Function|null} indicatorTitle Indicator title text, a function that returns text, or
2584 * `null` for no indicator title
2587 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
2588 indicatorTitle
= typeof indicatorTitle
=== 'function' ||
2589 ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ?
2590 OO
.ui
.resolveMsg( indicatorTitle
) : null;
2592 if ( this.indicatorTitle
!== indicatorTitle
) {
2593 this.indicatorTitle
= indicatorTitle
;
2594 if ( this.$indicator
) {
2595 if ( this.indicatorTitle
!== null ) {
2596 this.$indicator
.attr( 'title', indicatorTitle
);
2598 this.$indicator
.removeAttr( 'title' );
2607 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2609 * @return {string} Symbolic name of indicator
2611 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
2612 return this.indicator
;
2616 * Get the indicator title.
2618 * The title is displayed when a user moves the mouse over the indicator.
2620 * @return {string} Indicator title text
2622 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
2623 return this.indicatorTitle
;
2627 * LabelElement is often mixed into other classes to generate a label, which
2628 * helps identify the function of an interface element.
2629 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
2631 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2637 * @param {Object} [config] Configuration options
2638 * @cfg {jQuery} [$label] The label element created by the class. If this
2639 * configuration is omitted, the label element will use a generated `<span>`.
2640 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
2641 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
2642 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
2643 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2645 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
2646 // Configuration initialization
2647 config
= config
|| {};
2654 this.setLabel( config
.label
|| this.constructor.static.label
);
2655 this.setLabelElement( config
.$label
|| $( '<span>' ) );
2660 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
2665 * @event labelChange
2666 * @param {string} value
2669 /* Static Properties */
2672 * The label text. The label can be specified as a plaintext string, a function that will
2673 * produce a string in the future, or `null` for no label. The static value will
2674 * be overridden if a label is specified with the #label config option.
2678 * @property {string|Function|null}
2680 OO
.ui
.mixin
.LabelElement
.static.label
= null;
2682 /* Static methods */
2685 * Highlight the first occurrence of the query in the given text
2687 * @param {string} text Text
2688 * @param {string} query Query to find
2689 * @return {jQuery} Text with the first match of the query
2690 * sub-string wrapped in highlighted span
2692 OO
.ui
.mixin
.LabelElement
.static.highlightQuery = function ( text
, query
) {
2693 var $result
= $( '<span>' ),
2694 offset
= text
.toLowerCase().indexOf( query
.toLowerCase() );
2696 if ( !query
.length
|| offset
=== -1 ) {
2697 return $result
.text( text
);
2700 document
.createTextNode( text
.slice( 0, offset
) ),
2702 .addClass( 'oo-ui-labelElement-label-highlight' )
2703 .text( text
.slice( offset
, offset
+ query
.length
) ),
2704 document
.createTextNode( text
.slice( offset
+ query
.length
) )
2706 return $result
.contents();
2712 * Set the label element.
2714 * If an element is already set, it will be cleaned up before setting up the new element.
2716 * @param {jQuery} $label Element to use as label
2718 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
2719 if ( this.$label
) {
2720 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
2723 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
2724 this.setLabelContent( this.label
);
2730 * An empty string will result in the label being hidden. A string containing only whitespace will
2731 * be converted to a single ` `.
2733 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
2734 * text; or null for no label
2737 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
2738 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
2739 label
= ( ( typeof label
=== 'string' && label
.length
) || label
instanceof jQuery
|| label
instanceof OO
.ui
.HtmlSnippet
) ? label
: null;
2741 this.$element
.toggleClass( 'oo-ui-labelElement', !!label
);
2743 if ( this.label
!== label
) {
2744 if ( this.$label
) {
2745 this.setLabelContent( label
);
2748 this.emit( 'labelChange' );
2755 * Set the label as plain text with a highlighted query
2757 * @param {string} text Text label to set
2758 * @param {string} query Substring of text to highlight
2761 OO
.ui
.mixin
.LabelElement
.prototype.setHighlightedQuery = function ( text
, query
) {
2762 return this.setLabel( this.constructor.static.highlightQuery( text
, query
) );
2768 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
2769 * text; or null for no label
2771 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
2779 * @deprecated since 0.16.0
2781 OO
.ui
.mixin
.LabelElement
.prototype.fitLabel = function () {
2786 * Set the content of the label.
2788 * Do not call this method until after the label element has been set by #setLabelElement.
2791 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
2792 * text; or null for no label
2794 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
2795 if ( typeof label
=== 'string' ) {
2796 if ( label
.match( /^\s*$/ ) ) {
2797 // Convert whitespace only string to a single non-breaking space
2798 this.$label
.html( ' ' );
2800 this.$label
.text( label
);
2802 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
2803 this.$label
.html( label
.toString() );
2804 } else if ( label
instanceof jQuery
) {
2805 this.$label
.empty().append( label
);
2807 this.$label
.empty();
2812 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
2813 * additional functionality to an element created by another class. The class provides
2814 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
2815 * which are used to customize the look and feel of a widget to better describe its
2816 * importance and functionality.
2818 * The library currently contains the following styling flags for general use:
2820 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
2821 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
2822 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
2824 * The flags affect the appearance of the buttons:
2827 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
2828 * var button1 = new OO.ui.ButtonWidget( {
2829 * label: 'Constructive',
2830 * flags: 'constructive'
2832 * var button2 = new OO.ui.ButtonWidget( {
2833 * label: 'Destructive',
2834 * flags: 'destructive'
2836 * var button3 = new OO.ui.ButtonWidget( {
2837 * label: 'Progressive',
2838 * flags: 'progressive'
2840 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
2842 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
2843 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
2845 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
2851 * @param {Object} [config] Configuration options
2852 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
2853 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
2854 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
2855 * @cfg {jQuery} [$flagged] The flagged element. By default,
2856 * the flagged functionality is applied to the element created by the class ($element).
2857 * If a different element is specified, the flagged functionality will be applied to it instead.
2859 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
2860 // Configuration initialization
2861 config
= config
|| {};
2865 this.$flagged
= null;
2868 this.setFlags( config
.flags
);
2869 this.setFlaggedElement( config
.$flagged
|| this.$element
);
2876 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
2877 * parameter contains the name of each modified flag and indicates whether it was
2880 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
2881 * that the flag was added, `false` that the flag was removed.
2887 * Set the flagged element.
2889 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
2890 * If an element is already set, the method will remove the mixin’s effect on that element.
2892 * @param {jQuery} $flagged Element that should be flagged
2894 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
2895 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
2896 return 'oo-ui-flaggedElement-' + flag
;
2899 if ( this.$flagged
) {
2900 this.$flagged
.removeClass( classNames
);
2903 this.$flagged
= $flagged
.addClass( classNames
);
2907 * Check if the specified flag is set.
2909 * @param {string} flag Name of flag
2910 * @return {boolean} The flag is set
2912 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
2913 // This may be called before the constructor, thus before this.flags is set
2914 return this.flags
&& ( flag
in this.flags
);
2918 * Get the names of all flags set.
2920 * @return {string[]} Flag names
2922 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
2923 // This may be called before the constructor, thus before this.flags is set
2924 return Object
.keys( this.flags
|| {} );
2933 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
2934 var flag
, className
,
2937 classPrefix
= 'oo-ui-flaggedElement-';
2939 for ( flag
in this.flags
) {
2940 className
= classPrefix
+ flag
;
2941 changes
[ flag
] = false;
2942 delete this.flags
[ flag
];
2943 remove
.push( className
);
2946 if ( this.$flagged
) {
2947 this.$flagged
.removeClass( remove
.join( ' ' ) );
2950 this.updateThemeClasses();
2951 this.emit( 'flag', changes
);
2957 * Add one or more flags.
2959 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
2960 * or an object keyed by flag name with a boolean value that indicates whether the flag should
2961 * be added (`true`) or removed (`false`).
2965 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
2966 var i
, len
, flag
, className
,
2970 classPrefix
= 'oo-ui-flaggedElement-';
2972 if ( typeof flags
=== 'string' ) {
2973 className
= classPrefix
+ flags
;
2975 if ( !this.flags
[ flags
] ) {
2976 this.flags
[ flags
] = true;
2977 add
.push( className
);
2979 } else if ( Array
.isArray( flags
) ) {
2980 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
2982 className
= classPrefix
+ flag
;
2984 if ( !this.flags
[ flag
] ) {
2985 changes
[ flag
] = true;
2986 this.flags
[ flag
] = true;
2987 add
.push( className
);
2990 } else if ( OO
.isPlainObject( flags
) ) {
2991 for ( flag
in flags
) {
2992 className
= classPrefix
+ flag
;
2993 if ( flags
[ flag
] ) {
2995 if ( !this.flags
[ flag
] ) {
2996 changes
[ flag
] = true;
2997 this.flags
[ flag
] = true;
2998 add
.push( className
);
3002 if ( this.flags
[ flag
] ) {
3003 changes
[ flag
] = false;
3004 delete this.flags
[ flag
];
3005 remove
.push( className
);
3011 if ( this.$flagged
) {
3013 .addClass( add
.join( ' ' ) )
3014 .removeClass( remove
.join( ' ' ) );
3017 this.updateThemeClasses();
3018 this.emit( 'flag', changes
);
3024 * TitledElement is mixed into other classes to provide a `title` attribute.
3025 * Titles are rendered by the browser and are made visible when the user moves
3026 * the mouse over the element. Titles are not visible on touch devices.
3029 * // TitledElement provides a 'title' attribute to the
3030 * // ButtonWidget class
3031 * var button = new OO.ui.ButtonWidget( {
3032 * label: 'Button with Title',
3033 * title: 'I am a button'
3035 * $( 'body' ).append( button.$element );
3041 * @param {Object} [config] Configuration options
3042 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
3043 * If this config is omitted, the title functionality is applied to $element, the
3044 * element created by the class.
3045 * @cfg {string|Function} [title] The title text or a function that returns text. If
3046 * this config is omitted, the value of the {@link #static-title static title} property is used.
3048 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
3049 // Configuration initialization
3050 config
= config
|| {};
3053 this.$titled
= null;
3057 this.setTitle( config
.title
|| this.constructor.static.title
);
3058 this.setTitledElement( config
.$titled
|| this.$element
);
3063 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
3065 /* Static Properties */
3068 * The title text, a function that returns text, or `null` for no title. The value of the static property
3069 * is overridden if the #title config option is used.
3073 * @property {string|Function|null}
3075 OO
.ui
.mixin
.TitledElement
.static.title
= null;
3080 * Set the titled element.
3082 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
3083 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
3085 * @param {jQuery} $titled Element that should use the 'titled' functionality
3087 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
3088 if ( this.$titled
) {
3089 this.$titled
.removeAttr( 'title' );
3092 this.$titled
= $titled
;
3094 this.$titled
.attr( 'title', this.title
);
3101 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
3104 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
3105 title
= typeof title
=== 'function' ? OO
.ui
.resolveMsg( title
) : title
;
3106 title
= ( typeof title
=== 'string' && title
.length
) ? title
: null;
3108 if ( this.title
!== title
) {
3109 if ( this.$titled
) {
3110 if ( title
!== null ) {
3111 this.$titled
.attr( 'title', title
);
3113 this.$titled
.removeAttr( 'title' );
3125 * @return {string} Title string
3127 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
3132 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
3133 * Accesskeys allow an user to go to a specific element by using
3134 * a shortcut combination of a browser specific keys + the key
3138 * // AccessKeyedElement provides an 'accesskey' attribute to the
3139 * // ButtonWidget class
3140 * var button = new OO.ui.ButtonWidget( {
3141 * label: 'Button with Accesskey',
3144 * $( 'body' ).append( button.$element );
3150 * @param {Object} [config] Configuration options
3151 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3152 * If this config is omitted, the accesskey functionality is applied to $element, the
3153 * element created by the class.
3154 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3155 * this config is omitted, no accesskey will be added.
3157 OO
.ui
.mixin
.AccessKeyedElement
= function OoUiMixinAccessKeyedElement( config
) {
3158 // Configuration initialization
3159 config
= config
|| {};
3162 this.$accessKeyed
= null;
3163 this.accessKey
= null;
3166 this.setAccessKey( config
.accessKey
|| null );
3167 this.setAccessKeyedElement( config
.$accessKeyed
|| this.$element
);
3172 OO
.initClass( OO
.ui
.mixin
.AccessKeyedElement
);
3174 /* Static Properties */
3177 * The access key, a function that returns a key, or `null` for no accesskey.
3181 * @property {string|Function|null}
3183 OO
.ui
.mixin
.AccessKeyedElement
.static.accessKey
= null;
3188 * Set the accesskeyed element.
3190 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
3191 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
3193 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
3195 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKeyedElement = function ( $accessKeyed
) {
3196 if ( this.$accessKeyed
) {
3197 this.$accessKeyed
.removeAttr( 'accesskey' );
3200 this.$accessKeyed
= $accessKeyed
;
3201 if ( this.accessKey
) {
3202 this.$accessKeyed
.attr( 'accesskey', this.accessKey
);
3209 * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no accesskey
3212 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKey = function ( accessKey
) {
3213 accessKey
= typeof accessKey
=== 'string' ? OO
.ui
.resolveMsg( accessKey
) : null;
3215 if ( this.accessKey
!== accessKey
) {
3216 if ( this.$accessKeyed
) {
3217 if ( accessKey
!== null ) {
3218 this.$accessKeyed
.attr( 'accesskey', accessKey
);
3220 this.$accessKeyed
.removeAttr( 'accesskey' );
3223 this.accessKey
= accessKey
;
3232 * @return {string} accessKey string
3234 OO
.ui
.mixin
.AccessKeyedElement
.prototype.getAccessKey = function () {
3235 return this.accessKey
;
3239 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3240 * feels, and functionality can be customized via the class’s configuration options
3241 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
3244 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
3247 * // A button widget
3248 * var button = new OO.ui.ButtonWidget( {
3249 * label: 'Button with Icon',
3251 * iconTitle: 'Remove'
3253 * $( 'body' ).append( button.$element );
3255 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3258 * @extends OO.ui.Widget
3259 * @mixins OO.ui.mixin.ButtonElement
3260 * @mixins OO.ui.mixin.IconElement
3261 * @mixins OO.ui.mixin.IndicatorElement
3262 * @mixins OO.ui.mixin.LabelElement
3263 * @mixins OO.ui.mixin.TitledElement
3264 * @mixins OO.ui.mixin.FlaggedElement
3265 * @mixins OO.ui.mixin.TabIndexedElement
3266 * @mixins OO.ui.mixin.AccessKeyedElement
3269 * @param {Object} [config] Configuration options
3270 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3271 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3272 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3274 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
3275 // Configuration initialization
3276 config
= config
|| {};
3278 // Parent constructor
3279 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
3281 // Mixin constructors
3282 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
3283 OO
.ui
.mixin
.IconElement
.call( this, config
);
3284 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
3285 OO
.ui
.mixin
.LabelElement
.call( this, config
);
3286 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
3287 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
3288 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
3289 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$button
} ) );
3294 this.noFollow
= false;
3297 this.connect( this, { disable
: 'onDisable' } );
3300 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
3302 .addClass( 'oo-ui-buttonWidget' )
3303 .append( this.$button
);
3304 this.setHref( config
.href
);
3305 this.setTarget( config
.target
);
3306 this.setNoFollow( config
.noFollow
);
3311 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
3312 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
3313 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
3314 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
3315 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
3316 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
3317 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
3318 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
3319 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
3326 OO
.ui
.ButtonWidget
.prototype.onMouseDown = function ( e
) {
3327 if ( !this.isDisabled() ) {
3328 // Remove the tab-index while the button is down to prevent the button from stealing focus
3329 this.$button
.removeAttr( 'tabindex' );
3332 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown
.call( this, e
);
3338 OO
.ui
.ButtonWidget
.prototype.onMouseUp = function ( e
) {
3339 if ( !this.isDisabled() ) {
3340 // Restore the tab-index after the button is up to restore the button's accessibility
3341 this.$button
.attr( 'tabindex', this.tabIndex
);
3344 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp
.call( this, e
);
3348 * Get hyperlink location.
3350 * @return {string} Hyperlink location
3352 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
3357 * Get hyperlink target.
3359 * @return {string} Hyperlink target
3361 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
3366 * Get search engine traversal hint.
3368 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3370 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
3371 return this.noFollow
;
3375 * Set hyperlink location.
3377 * @param {string|null} href Hyperlink location, null to remove
3379 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
3380 href
= typeof href
=== 'string' ? href
: null;
3381 if ( href
!== null && !OO
.ui
.isSafeUrl( href
) ) {
3385 if ( href
!== this.href
) {
3394 * Update the `href` attribute, in case of changes to href or
3400 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
3401 if ( this.href
!== null && !this.isDisabled() ) {
3402 this.$button
.attr( 'href', this.href
);
3404 this.$button
.removeAttr( 'href' );
3411 * Handle disable events.
3414 * @param {boolean} disabled Element is disabled
3416 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
3421 * Set hyperlink target.
3423 * @param {string|null} target Hyperlink target, null to remove
3425 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
3426 target
= typeof target
=== 'string' ? target
: null;
3428 if ( target
!== this.target
) {
3429 this.target
= target
;
3430 if ( target
!== null ) {
3431 this.$button
.attr( 'target', target
);
3433 this.$button
.removeAttr( 'target' );
3441 * Set search engine traversal hint.
3443 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3445 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
3446 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
3448 if ( noFollow
!== this.noFollow
) {
3449 this.noFollow
= noFollow
;
3451 this.$button
.attr( 'rel', 'nofollow' );
3453 this.$button
.removeAttr( 'rel' );
3461 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3462 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3463 * removed, and cleared from the group.
3466 * // Example: A ButtonGroupWidget with two buttons
3467 * var button1 = new OO.ui.PopupButtonWidget( {
3468 * label: 'Select a category',
3471 * $content: $( '<p>List of categories...</p>' ),
3476 * var button2 = new OO.ui.ButtonWidget( {
3479 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
3480 * items: [button1, button2]
3482 * $( 'body' ).append( buttonGroup.$element );
3485 * @extends OO.ui.Widget
3486 * @mixins OO.ui.mixin.GroupElement
3489 * @param {Object} [config] Configuration options
3490 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
3492 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
3493 // Configuration initialization
3494 config
= config
|| {};
3496 // Parent constructor
3497 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
3499 // Mixin constructors
3500 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
3503 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
3504 if ( Array
.isArray( config
.items
) ) {
3505 this.addItems( config
.items
);
3511 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
3512 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
3515 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
3516 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
3517 * for a list of icons included in the library.
3520 * // An icon widget with a label
3521 * var myIcon = new OO.ui.IconWidget( {
3525 * // Create a label.
3526 * var iconLabel = new OO.ui.LabelWidget( {
3529 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
3531 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
3534 * @extends OO.ui.Widget
3535 * @mixins OO.ui.mixin.IconElement
3536 * @mixins OO.ui.mixin.TitledElement
3537 * @mixins OO.ui.mixin.FlaggedElement
3540 * @param {Object} [config] Configuration options
3542 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
3543 // Configuration initialization
3544 config
= config
|| {};
3546 // Parent constructor
3547 OO
.ui
.IconWidget
.parent
.call( this, config
);
3549 // Mixin constructors
3550 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
3551 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
3552 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
3555 this.$element
.addClass( 'oo-ui-iconWidget' );
3560 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
3561 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
3562 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
3563 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
3565 /* Static Properties */
3567 OO
.ui
.IconWidget
.static.tagName
= 'span';
3570 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
3571 * attention to the status of an item or to clarify the function of a control. For a list of
3572 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
3575 * // Example of an indicator widget
3576 * var indicator1 = new OO.ui.IndicatorWidget( {
3577 * indicator: 'alert'
3580 * // Create a fieldset layout to add a label
3581 * var fieldset = new OO.ui.FieldsetLayout();
3582 * fieldset.addItems( [
3583 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
3585 * $( 'body' ).append( fieldset.$element );
3587 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3590 * @extends OO.ui.Widget
3591 * @mixins OO.ui.mixin.IndicatorElement
3592 * @mixins OO.ui.mixin.TitledElement
3595 * @param {Object} [config] Configuration options
3597 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
3598 // Configuration initialization
3599 config
= config
|| {};
3601 // Parent constructor
3602 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
3604 // Mixin constructors
3605 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
3606 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
3609 this.$element
.addClass( 'oo-ui-indicatorWidget' );
3614 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
3615 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
3616 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
3618 /* Static Properties */
3620 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
3623 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
3624 * be configured with a `label` option that is set to a string, a label node, or a function:
3626 * - String: a plaintext string
3627 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
3628 * label that includes a link or special styling, such as a gray color or additional graphical elements.
3629 * - Function: a function that will produce a string in the future. Functions are used
3630 * in cases where the value of the label is not currently defined.
3632 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
3633 * will come into focus when the label is clicked.
3636 * // Examples of LabelWidgets
3637 * var label1 = new OO.ui.LabelWidget( {
3638 * label: 'plaintext label'
3640 * var label2 = new OO.ui.LabelWidget( {
3641 * label: $( '<a href="default.html">jQuery label</a>' )
3643 * // Create a fieldset layout with fields for each example
3644 * var fieldset = new OO.ui.FieldsetLayout();
3645 * fieldset.addItems( [
3646 * new OO.ui.FieldLayout( label1 ),
3647 * new OO.ui.FieldLayout( label2 )
3649 * $( 'body' ).append( fieldset.$element );
3652 * @extends OO.ui.Widget
3653 * @mixins OO.ui.mixin.LabelElement
3656 * @param {Object} [config] Configuration options
3657 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
3658 * Clicking the label will focus the specified input field.
3660 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
3661 // Configuration initialization
3662 config
= config
|| {};
3664 // Parent constructor
3665 OO
.ui
.LabelWidget
.parent
.call( this, config
);
3667 // Mixin constructors
3668 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
3669 OO
.ui
.mixin
.TitledElement
.call( this, config
);
3672 this.input
= config
.input
;
3675 if ( this.input
instanceof OO
.ui
.InputWidget
) {
3676 this.$element
.on( 'click', this.onClick
.bind( this ) );
3680 this.$element
.addClass( 'oo-ui-labelWidget' );
3685 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
3686 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
3687 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
3689 /* Static Properties */
3691 OO
.ui
.LabelWidget
.static.tagName
= 'span';
3696 * Handles label mouse click events.
3699 * @param {jQuery.Event} e Mouse click event
3701 OO
.ui
.LabelWidget
.prototype.onClick = function () {
3702 this.input
.simulateLabelClick();
3707 * PendingElement is a mixin that is used to create elements that notify users that something is happening
3708 * and that they should wait before proceeding. The pending state is visually represented with a pending
3709 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
3710 * field of a {@link OO.ui.TextInputWidget text input widget}.
3712 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
3713 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
3714 * in process dialogs.
3717 * function MessageDialog( config ) {
3718 * MessageDialog.parent.call( this, config );
3720 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
3722 * MessageDialog.static.actions = [
3723 * { action: 'save', label: 'Done', flags: 'primary' },
3724 * { label: 'Cancel', flags: 'safe' }
3727 * MessageDialog.prototype.initialize = function () {
3728 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
3729 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
3730 * this.content.$element.append( '<p>Click the \'Done\' action widget to see its pending state. Note that action widgets can be marked pending in message dialogs but not process dialogs.</p>' );
3731 * this.$body.append( this.content.$element );
3733 * MessageDialog.prototype.getBodyHeight = function () {
3736 * MessageDialog.prototype.getActionProcess = function ( action ) {
3737 * var dialog = this;
3738 * if ( action === 'save' ) {
3739 * dialog.getActions().get({actions: 'save'})[0].pushPending();
3740 * return new OO.ui.Process()
3742 * .next( function () {
3743 * dialog.getActions().get({actions: 'save'})[0].popPending();
3746 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
3749 * var windowManager = new OO.ui.WindowManager();
3750 * $( 'body' ).append( windowManager.$element );
3752 * var dialog = new MessageDialog();
3753 * windowManager.addWindows( [ dialog ] );
3754 * windowManager.openWindow( dialog );
3760 * @param {Object} [config] Configuration options
3761 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
3763 OO
.ui
.mixin
.PendingElement
= function OoUiMixinPendingElement( config
) {
3764 // Configuration initialization
3765 config
= config
|| {};
3769 this.$pending
= null;
3772 this.setPendingElement( config
.$pending
|| this.$element
);
3777 OO
.initClass( OO
.ui
.mixin
.PendingElement
);
3782 * Set the pending element (and clean up any existing one).
3784 * @param {jQuery} $pending The element to set to pending.
3786 OO
.ui
.mixin
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
3787 if ( this.$pending
) {
3788 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
3791 this.$pending
= $pending
;
3792 if ( this.pending
> 0 ) {
3793 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
3798 * Check if an element is pending.
3800 * @return {boolean} Element is pending
3802 OO
.ui
.mixin
.PendingElement
.prototype.isPending = function () {
3803 return !!this.pending
;
3807 * Increase the pending counter. The pending state will remain active until the counter is zero
3808 * (i.e., the number of calls to #pushPending and #popPending is the same).
3812 OO
.ui
.mixin
.PendingElement
.prototype.pushPending = function () {
3813 if ( this.pending
=== 0 ) {
3814 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
3815 this.updateThemeClasses();
3823 * Decrease the pending counter. The pending state will remain active until the counter is zero
3824 * (i.e., the number of calls to #pushPending and #popPending is the same).
3828 OO
.ui
.mixin
.PendingElement
.prototype.popPending = function () {
3829 if ( this.pending
=== 1 ) {
3830 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
3831 this.updateThemeClasses();
3833 this.pending
= Math
.max( 0, this.pending
- 1 );
3839 * Element that can be automatically clipped to visible boundaries.
3841 * Whenever the element's natural height changes, you have to call
3842 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
3843 * clipping correctly.
3845 * The dimensions of #$clippableContainer will be compared to the boundaries of the
3846 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
3847 * then #$clippable will be given a fixed reduced height and/or width and will be made
3848 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
3849 * but you can build a static footer by setting #$clippableContainer to an element that contains
3850 * #$clippable and the footer.
3856 * @param {Object} [config] Configuration options
3857 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
3858 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
3859 * omit to use #$clippable
3861 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
3862 // Configuration initialization
3863 config
= config
|| {};
3866 this.$clippable
= null;
3867 this.$clippableContainer
= null;
3868 this.clipping
= false;
3869 this.clippedHorizontally
= false;
3870 this.clippedVertically
= false;
3871 this.$clippableScrollableContainer
= null;
3872 this.$clippableScroller
= null;
3873 this.$clippableWindow
= null;
3874 this.idealWidth
= null;
3875 this.idealHeight
= null;
3876 this.onClippableScrollHandler
= this.clip
.bind( this );
3877 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
3880 if ( config
.$clippableContainer
) {
3881 this.setClippableContainer( config
.$clippableContainer
);
3883 this.setClippableElement( config
.$clippable
|| this.$element
);
3889 * Set clippable element.
3891 * If an element is already set, it will be cleaned up before setting up the new element.
3893 * @param {jQuery} $clippable Element to make clippable
3895 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
3896 if ( this.$clippable
) {
3897 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
3898 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
3899 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
3902 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
3907 * Set clippable container.
3909 * This is the container that will be measured when deciding whether to clip. When clipping,
3910 * #$clippable will be resized in order to keep the clippable container fully visible.
3912 * If the clippable container is unset, #$clippable will be used.
3914 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
3916 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableContainer = function ( $clippableContainer
) {
3917 this.$clippableContainer
= $clippableContainer
;
3918 if ( this.$clippable
) {
3926 * Do not turn clipping on until after the element is attached to the DOM and visible.
3928 * @param {boolean} [clipping] Enable clipping, omit to toggle
3931 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
3932 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
3934 if ( this.clipping
!== clipping
) {
3935 this.clipping
= clipping
;
3937 this.$clippableScrollableContainer
= $( this.getClosestScrollableElementContainer() );
3938 // If the clippable container is the root, we have to listen to scroll events and check
3939 // jQuery.scrollTop on the window because of browser inconsistencies
3940 this.$clippableScroller
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
3941 $( OO
.ui
.Element
.static.getWindow( this.$clippableScrollableContainer
) ) :
3942 this.$clippableScrollableContainer
;
3943 this.$clippableScroller
.on( 'scroll', this.onClippableScrollHandler
);
3944 this.$clippableWindow
= $( this.getElementWindow() )
3945 .on( 'resize', this.onClippableWindowResizeHandler
);
3946 // Initial clip after visible
3949 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
3950 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
3952 this.$clippableScrollableContainer
= null;
3953 this.$clippableScroller
.off( 'scroll', this.onClippableScrollHandler
);
3954 this.$clippableScroller
= null;
3955 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
3956 this.$clippableWindow
= null;
3964 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
3966 * @return {boolean} Element will be clipped to the visible area
3968 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
3969 return this.clipping
;
3973 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
3975 * @return {boolean} Part of the element is being clipped
3977 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
3978 return this.clippedHorizontally
|| this.clippedVertically
;
3982 * Check if the right of the element is being clipped by the nearest scrollable container.
3984 * @return {boolean} Part of the element is being clipped
3986 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
3987 return this.clippedHorizontally
;
3991 * Check if the bottom of the element is being clipped by the nearest scrollable container.
3993 * @return {boolean} Part of the element is being clipped
3995 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
3996 return this.clippedVertically
;
4000 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
4002 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
4003 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
4005 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
4006 this.idealWidth
= width
;
4007 this.idealHeight
= height
;
4009 if ( !this.clipping
) {
4010 // Update dimensions
4011 this.$clippable
.css( { width
: width
, height
: height
} );
4013 // While clipping, idealWidth and idealHeight are not considered
4017 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
4018 * the element's natural height changes.
4020 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
4021 * overlapped by, the visible area of the nearest scrollable container.
4025 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
4026 var $container
, extraHeight
, extraWidth
, ccOffset
,
4027 $scrollableContainer
, scOffset
, scHeight
, scWidth
,
4028 ccWidth
, scrollerIsWindow
, scrollTop
, scrollLeft
,
4029 desiredWidth
, desiredHeight
, allotedWidth
, allotedHeight
,
4030 naturalWidth
, naturalHeight
, clipWidth
, clipHeight
,
4031 buffer
= 7; // Chosen by fair dice roll
4033 if ( !this.clipping
) {
4034 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
4038 $container
= this.$clippableContainer
|| this.$clippable
;
4039 extraHeight
= $container
.outerHeight() - this.$clippable
.outerHeight();
4040 extraWidth
= $container
.outerWidth() - this.$clippable
.outerWidth();
4041 ccOffset
= $container
.offset();
4042 $scrollableContainer
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
4043 this.$clippableWindow
: this.$clippableScrollableContainer
;
4044 scOffset
= $scrollableContainer
.offset() || { top
: 0, left
: 0 };
4045 scHeight
= $scrollableContainer
.innerHeight() - buffer
;
4046 scWidth
= $scrollableContainer
.innerWidth() - buffer
;
4047 ccWidth
= $container
.outerWidth() + buffer
;
4048 scrollerIsWindow
= this.$clippableScroller
[ 0 ] === this.$clippableWindow
[ 0 ];
4049 scrollTop
= scrollerIsWindow
? this.$clippableScroller
.scrollTop() : 0;
4050 scrollLeft
= scrollerIsWindow
? this.$clippableScroller
.scrollLeft() : 0;
4051 desiredWidth
= ccOffset
.left
< 0 ?
4052 ccWidth
+ ccOffset
.left
:
4053 ( scOffset
.left
+ scrollLeft
+ scWidth
) - ccOffset
.left
;
4054 desiredHeight
= ( scOffset
.top
+ scrollTop
+ scHeight
) - ccOffset
.top
;
4055 allotedWidth
= Math
.ceil( desiredWidth
- extraWidth
);
4056 allotedHeight
= Math
.ceil( desiredHeight
- extraHeight
);
4057 naturalWidth
= this.$clippable
.prop( 'scrollWidth' );
4058 naturalHeight
= this.$clippable
.prop( 'scrollHeight' );
4059 clipWidth
= allotedWidth
< naturalWidth
;
4060 clipHeight
= allotedHeight
< naturalHeight
;
4063 this.$clippable
.css( { overflowX
: 'scroll', width
: Math
.max( 0, allotedWidth
) } );
4065 this.$clippable
.css( { width
: this.idealWidth
? this.idealWidth
- extraWidth
: '', overflowX
: '' } );
4068 this.$clippable
.css( { overflowY
: 'scroll', height
: Math
.max( 0, allotedHeight
) } );
4070 this.$clippable
.css( { height
: this.idealHeight
? this.idealHeight
- extraHeight
: '', overflowY
: '' } );
4073 // If we stopped clipping in at least one of the dimensions
4074 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
4075 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4078 this.clippedHorizontally
= clipWidth
;
4079 this.clippedVertically
= clipHeight
;
4085 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
4086 * By default, each popup has an anchor that points toward its origin.
4087 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
4090 * // A popup widget.
4091 * var popup = new OO.ui.PopupWidget( {
4092 * $content: $( '<p>Hi there!</p>' ),
4097 * $( 'body' ).append( popup.$element );
4098 * // To display the popup, toggle the visibility to 'true'.
4099 * popup.toggle( true );
4101 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
4104 * @extends OO.ui.Widget
4105 * @mixins OO.ui.mixin.LabelElement
4106 * @mixins OO.ui.mixin.ClippableElement
4109 * @param {Object} [config] Configuration options
4110 * @cfg {number} [width=320] Width of popup in pixels
4111 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
4112 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
4113 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
4114 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
4115 * popup is leaning towards the right of the screen.
4116 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
4117 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
4118 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
4119 * sentence in the given language.
4120 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
4121 * See the [OOjs UI docs on MediaWiki][3] for an example.
4122 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
4123 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
4124 * @cfg {jQuery} [$content] Content to append to the popup's body
4125 * @cfg {jQuery} [$footer] Content to append to the popup's footer
4126 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
4127 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
4128 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
4130 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
4131 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
4133 * @cfg {boolean} [padded=false] Add padding to the popup's body
4135 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
4136 // Configuration initialization
4137 config
= config
|| {};
4139 // Parent constructor
4140 OO
.ui
.PopupWidget
.parent
.call( this, config
);
4142 // Properties (must be set before ClippableElement constructor call)
4143 this.$body
= $( '<div>' );
4144 this.$popup
= $( '<div>' );
4146 // Mixin constructors
4147 OO
.ui
.mixin
.LabelElement
.call( this, config
);
4148 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, {
4149 $clippable
: this.$body
,
4150 $clippableContainer
: this.$popup
4154 this.$anchor
= $( '<div>' );
4155 // If undefined, will be computed lazily in updateDimensions()
4156 this.$container
= config
.$container
;
4157 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
4158 this.autoClose
= !!config
.autoClose
;
4159 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
4160 this.transitionTimeout
= null;
4162 this.width
= config
.width
!== undefined ? config
.width
: 320;
4163 this.height
= config
.height
!== undefined ? config
.height
: null;
4164 this.setAlignment( config
.align
);
4165 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
4166 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
4169 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
4170 this.$body
.addClass( 'oo-ui-popupWidget-body' );
4171 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
4173 .addClass( 'oo-ui-popupWidget-popup' )
4174 .append( this.$body
);
4176 .addClass( 'oo-ui-popupWidget' )
4177 .append( this.$popup
, this.$anchor
);
4178 // Move content, which was added to #$element by OO.ui.Widget, to the body
4179 // FIXME This is gross, we should use '$body' or something for the config
4180 if ( config
.$content
instanceof jQuery
) {
4181 this.$body
.append( config
.$content
);
4184 if ( config
.padded
) {
4185 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
4188 if ( config
.head
) {
4189 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
4190 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
4191 this.$head
= $( '<div>' )
4192 .addClass( 'oo-ui-popupWidget-head' )
4193 .append( this.$label
, this.closeButton
.$element
);
4194 this.$popup
.prepend( this.$head
);
4197 if ( config
.$footer
) {
4198 this.$footer
= $( '<div>' )
4199 .addClass( 'oo-ui-popupWidget-footer' )
4200 .append( config
.$footer
);
4201 this.$popup
.append( this.$footer
);
4204 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
4205 // that reference properties not initialized at that time of parent class construction
4206 // TODO: Find a better way to handle post-constructor setup
4207 this.visible
= false;
4208 this.$element
.addClass( 'oo-ui-element-hidden' );
4213 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
4214 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
4215 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
4220 * Handles mouse down events.
4223 * @param {MouseEvent} e Mouse down event
4225 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
4228 !$.contains( this.$element
[ 0 ], e
.target
) &&
4229 ( !this.$autoCloseIgnore
|| !this.$autoCloseIgnore
.has( e
.target
).length
)
4231 this.toggle( false );
4236 * Bind mouse down listener.
4240 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
4241 // Capture clicks outside popup
4242 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler
, true );
4246 * Handles close button click events.
4250 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
4251 if ( this.isVisible() ) {
4252 this.toggle( false );
4257 * Unbind mouse down listener.
4261 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
4262 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler
, true );
4266 * Handles key down events.
4269 * @param {KeyboardEvent} e Key down event
4271 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
4273 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
4276 this.toggle( false );
4278 e
.stopPropagation();
4283 * Bind key down listener.
4287 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
4288 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
4292 * Unbind key down listener.
4296 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
4297 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
4301 * Show, hide, or toggle the visibility of the anchor.
4303 * @param {boolean} [show] Show anchor, omit to toggle
4305 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
4306 show
= show
=== undefined ? !this.anchored
: !!show
;
4308 if ( this.anchored
!== show
) {
4310 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
4312 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
4314 this.anchored
= show
;
4319 * Check if the anchor is visible.
4321 * @return {boolean} Anchor is visible
4323 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
4330 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
4332 show
= show
=== undefined ? !this.isVisible() : !!show
;
4334 change
= show
!== this.isVisible();
4337 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
4341 if ( this.autoClose
) {
4342 this.bindMouseDownListener();
4343 this.bindKeyDownListener();
4345 this.updateDimensions();
4346 this.toggleClipping( true );
4348 this.toggleClipping( false );
4349 if ( this.autoClose
) {
4350 this.unbindMouseDownListener();
4351 this.unbindKeyDownListener();
4360 * Set the size of the popup.
4362 * Changing the size may also change the popup's position depending on the alignment.
4364 * @param {number} width Width in pixels
4365 * @param {number} height Height in pixels
4366 * @param {boolean} [transition=false] Use a smooth transition
4369 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
4371 this.height
= height
!== undefined ? height
: null;
4372 if ( this.isVisible() ) {
4373 this.updateDimensions( transition
);
4378 * Update the size and position.
4380 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
4381 * be called automatically.
4383 * @param {boolean} [transition=false] Use a smooth transition
4386 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
4387 var popupOffset
, originOffset
, containerLeft
, containerWidth
, containerRight
,
4388 popupLeft
, popupRight
, overlapLeft
, overlapRight
, anchorWidth
,
4392 if ( !this.$container
) {
4393 // Lazy-initialize $container if not specified in constructor
4394 this.$container
= $( this.getClosestScrollableElementContainer() );
4397 // Set height and width before measuring things, since it might cause our measurements
4398 // to change (e.g. due to scrollbars appearing or disappearing)
4401 height
: this.height
!== null ? this.height
: 'auto'
4404 // If we are in RTL, we need to flip the alignment, unless it is center
4405 if ( align
=== 'forwards' || align
=== 'backwards' ) {
4406 if ( this.$container
.css( 'direction' ) === 'rtl' ) {
4407 align
= ( { forwards
: 'force-left', backwards
: 'force-right' } )[ this.align
];
4409 align
= ( { forwards
: 'force-right', backwards
: 'force-left' } )[ this.align
];
4414 // Compute initial popupOffset based on alignment
4415 popupOffset
= this.width
* ( { 'force-left': -1, center
: -0.5, 'force-right': 0 } )[ align
];
4417 // Figure out if this will cause the popup to go beyond the edge of the container
4418 originOffset
= this.$element
.offset().left
;
4419 containerLeft
= this.$container
.offset().left
;
4420 containerWidth
= this.$container
.innerWidth();
4421 containerRight
= containerLeft
+ containerWidth
;
4422 popupLeft
= popupOffset
- this.containerPadding
;
4423 popupRight
= popupOffset
+ this.containerPadding
+ this.width
+ this.containerPadding
;
4424 overlapLeft
= ( originOffset
+ popupLeft
) - containerLeft
;
4425 overlapRight
= containerRight
- ( originOffset
+ popupRight
);
4427 // Adjust offset to make the popup not go beyond the edge, if needed
4428 if ( overlapRight
< 0 ) {
4429 popupOffset
+= overlapRight
;
4430 } else if ( overlapLeft
< 0 ) {
4431 popupOffset
-= overlapLeft
;
4434 // Adjust offset to avoid anchor being rendered too close to the edge
4435 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
4436 // TODO: Find a measurement that works for CSS anchors and image anchors
4437 anchorWidth
= this.$anchor
[ 0 ].scrollWidth
* 2;
4438 if ( popupOffset
+ this.width
< anchorWidth
) {
4439 popupOffset
= anchorWidth
- this.width
;
4440 } else if ( -popupOffset
< anchorWidth
) {
4441 popupOffset
= -anchorWidth
;
4444 // Prevent transition from being interrupted
4445 clearTimeout( this.transitionTimeout
);
4447 // Enable transition
4448 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
4451 // Position body relative to anchor
4452 this.$popup
.css( 'margin-left', popupOffset
);
4455 // Prevent transitioning after transition is complete
4456 this.transitionTimeout
= setTimeout( function () {
4457 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
4460 // Prevent transitioning immediately
4461 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
4464 // Reevaluate clipping state since we've relocated and resized the popup
4471 * Set popup alignment
4473 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
4474 * `backwards` or `forwards`.
4476 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
4477 // Validate alignment and transform deprecated values
4478 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
4479 this.align
= { left
: 'force-right', right
: 'force-left' }[ align
] || align
;
4481 this.align
= 'center';
4486 * Get popup alignment
4488 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
4489 * `backwards` or `forwards`.
4491 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
4496 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
4497 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
4498 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
4499 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
4505 * @param {Object} [config] Configuration options
4506 * @cfg {Object} [popup] Configuration to pass to popup
4507 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
4509 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
4510 // Configuration initialization
4511 config
= config
|| {};
4514 this.popup
= new OO
.ui
.PopupWidget( $.extend(
4515 { autoClose
: true },
4517 { $autoCloseIgnore
: this.$element
}
4526 * @return {OO.ui.PopupWidget} Popup widget
4528 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
4533 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
4534 * which is used to display additional information or options.
4537 * // Example of a popup button.
4538 * var popupButton = new OO.ui.PopupButtonWidget( {
4539 * label: 'Popup button with options',
4542 * $content: $( '<p>Additional options here.</p>' ),
4544 * align: 'force-left'
4547 * // Append the button to the DOM.
4548 * $( 'body' ).append( popupButton.$element );
4551 * @extends OO.ui.ButtonWidget
4552 * @mixins OO.ui.mixin.PopupElement
4555 * @param {Object} [config] Configuration options
4557 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
4558 // Parent constructor
4559 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
4561 // Mixin constructors
4562 OO
.ui
.mixin
.PopupElement
.call( this, config
);
4565 this.connect( this, { click
: 'onAction' } );
4569 .addClass( 'oo-ui-popupButtonWidget' )
4570 .attr( 'aria-haspopup', 'true' )
4571 .append( this.popup
.$element
);
4576 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
4577 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
4582 * Handle the button action being triggered.
4586 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
4587 this.popup
.toggle();
4591 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
4593 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
4598 * @extends OO.ui.mixin.GroupElement
4601 * @param {Object} [config] Configuration options
4603 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
4604 // Parent constructor
4605 OO
.ui
.mixin
.GroupWidget
.parent
.call( this, config
);
4610 OO
.inheritClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
4615 * Set the disabled state of the widget.
4617 * This will also update the disabled state of child widgets.
4619 * @param {boolean} disabled Disable widget
4622 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
4626 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
4627 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
4629 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
4631 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4632 this.items
[ i
].updateDisabled();
4640 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
4642 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
4643 * allows bidirectional communication.
4645 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
4653 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
4660 * Check if widget is disabled.
4662 * Checks parent if present, making disabled state inheritable.
4664 * @return {boolean} Widget is disabled
4666 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
4667 return this.disabled
||
4668 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
4672 * Set group element is in.
4674 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
4677 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
4679 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
4680 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
4682 // Initialize item disabled states
4683 this.updateDisabled();
4689 * OptionWidgets are special elements that can be selected and configured with data. The
4690 * data is often unique for each option, but it does not have to be. OptionWidgets are used
4691 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
4692 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
4694 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
4697 * @extends OO.ui.Widget
4698 * @mixins OO.ui.mixin.LabelElement
4699 * @mixins OO.ui.mixin.FlaggedElement
4702 * @param {Object} [config] Configuration options
4704 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
4705 // Configuration initialization
4706 config
= config
|| {};
4708 // Parent constructor
4709 OO
.ui
.OptionWidget
.parent
.call( this, config
);
4711 // Mixin constructors
4712 OO
.ui
.mixin
.ItemWidget
.call( this );
4713 OO
.ui
.mixin
.LabelElement
.call( this, config
);
4714 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
4717 this.selected
= false;
4718 this.highlighted
= false;
4719 this.pressed
= false;
4723 .data( 'oo-ui-optionWidget', this )
4724 .attr( 'role', 'option' )
4725 .attr( 'aria-selected', 'false' )
4726 .addClass( 'oo-ui-optionWidget' )
4727 .append( this.$label
);
4732 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
4733 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
4734 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
4735 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
4737 /* Static Properties */
4739 OO
.ui
.OptionWidget
.static.selectable
= true;
4741 OO
.ui
.OptionWidget
.static.highlightable
= true;
4743 OO
.ui
.OptionWidget
.static.pressable
= true;
4745 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
4750 * Check if the option can be selected.
4752 * @return {boolean} Item is selectable
4754 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
4755 return this.constructor.static.selectable
&& !this.isDisabled() && this.isVisible();
4759 * Check if the option can be highlighted. A highlight indicates that the option
4760 * may be selected when a user presses enter or clicks. Disabled items cannot
4763 * @return {boolean} Item is highlightable
4765 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
4766 return this.constructor.static.highlightable
&& !this.isDisabled() && this.isVisible();
4770 * Check if the option can be pressed. The pressed state occurs when a user mouses
4771 * down on an item, but has not yet let go of the mouse.
4773 * @return {boolean} Item is pressable
4775 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
4776 return this.constructor.static.pressable
&& !this.isDisabled() && this.isVisible();
4780 * Check if the option is selected.
4782 * @return {boolean} Item is selected
4784 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
4785 return this.selected
;
4789 * Check if the option is highlighted. A highlight indicates that the
4790 * item may be selected when a user presses enter or clicks.
4792 * @return {boolean} Item is highlighted
4794 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
4795 return this.highlighted
;
4799 * Check if the option is pressed. The pressed state occurs when a user mouses
4800 * down on an item, but has not yet let go of the mouse. The item may appear
4801 * selected, but it will not be selected until the user releases the mouse.
4803 * @return {boolean} Item is pressed
4805 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
4806 return this.pressed
;
4810 * Set the option’s selected state. In general, all modifications to the selection
4811 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
4812 * method instead of this method.
4814 * @param {boolean} [state=false] Select option
4817 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
4818 if ( this.constructor.static.selectable
) {
4819 this.selected
= !!state
;
4821 .toggleClass( 'oo-ui-optionWidget-selected', state
)
4822 .attr( 'aria-selected', state
.toString() );
4823 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
4824 this.scrollElementIntoView();
4826 this.updateThemeClasses();
4832 * Set the option’s highlighted state. In general, all programmatic
4833 * modifications to the highlight should be handled by the
4834 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
4835 * method instead of this method.
4837 * @param {boolean} [state=false] Highlight option
4840 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
4841 if ( this.constructor.static.highlightable
) {
4842 this.highlighted
= !!state
;
4843 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
4844 this.updateThemeClasses();
4850 * Set the option’s pressed state. In general, all
4851 * programmatic modifications to the pressed state should be handled by the
4852 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
4853 * method instead of this method.
4855 * @param {boolean} [state=false] Press option
4858 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
4859 if ( this.constructor.static.pressable
) {
4860 this.pressed
= !!state
;
4861 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
4862 this.updateThemeClasses();
4868 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
4869 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
4870 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
4873 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
4874 * information, please see the [OOjs UI documentation on MediaWiki][1].
4877 * // Example of a select widget with three options
4878 * var select = new OO.ui.SelectWidget( {
4880 * new OO.ui.OptionWidget( {
4882 * label: 'Option One',
4884 * new OO.ui.OptionWidget( {
4886 * label: 'Option Two',
4888 * new OO.ui.OptionWidget( {
4890 * label: 'Option Three',
4894 * $( 'body' ).append( select.$element );
4896 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
4900 * @extends OO.ui.Widget
4901 * @mixins OO.ui.mixin.GroupWidget
4904 * @param {Object} [config] Configuration options
4905 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
4906 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
4907 * the [OOjs UI documentation on MediaWiki] [2] for examples.
4908 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
4910 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
4911 // Configuration initialization
4912 config
= config
|| {};
4914 // Parent constructor
4915 OO
.ui
.SelectWidget
.parent
.call( this, config
);
4917 // Mixin constructors
4918 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
4921 this.pressed
= false;
4922 this.selecting
= null;
4923 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
4924 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
4925 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
4926 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
4927 this.keyPressBuffer
= '';
4928 this.keyPressBufferTimer
= null;
4929 this.blockMouseOverEvents
= 0;
4932 this.connect( this, {
4936 mousedown
: this.onMouseDown
.bind( this ),
4937 mouseover
: this.onMouseOver
.bind( this ),
4938 mouseleave
: this.onMouseLeave
.bind( this )
4943 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
4944 .attr( 'role', 'listbox' );
4945 if ( Array
.isArray( config
.items
) ) {
4946 this.addItems( config
.items
);
4952 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
4954 // Need to mixin base class as well
4955 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupElement
);
4956 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
4959 OO
.ui
.SelectWidget
.static.passAllFilter = function () {
4968 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
4970 * @param {OO.ui.OptionWidget|null} item Highlighted item
4976 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
4977 * pressed state of an option.
4979 * @param {OO.ui.OptionWidget|null} item Pressed item
4985 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
4987 * @param {OO.ui.OptionWidget|null} item Selected item
4992 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
4993 * @param {OO.ui.OptionWidget} item Chosen item
4999 * An `add` event is emitted when options are added to the select with the #addItems method.
5001 * @param {OO.ui.OptionWidget[]} items Added items
5002 * @param {number} index Index of insertion point
5008 * A `remove` event is emitted when options are removed from the select with the #clearItems
5009 * or #removeItems methods.
5011 * @param {OO.ui.OptionWidget[]} items Removed items
5017 * Handle mouse down events.
5020 * @param {jQuery.Event} e Mouse down event
5022 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
5025 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
5026 this.togglePressed( true );
5027 item
= this.getTargetItem( e
);
5028 if ( item
&& item
.isSelectable() ) {
5029 this.pressItem( item
);
5030 this.selecting
= item
;
5031 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
5032 this.getElementDocument().addEventListener( 'mousemove', this.onMouseMoveHandler
, true );
5039 * Handle mouse up events.
5042 * @param {MouseEvent} e Mouse up event
5044 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
5047 this.togglePressed( false );
5048 if ( !this.selecting
) {
5049 item
= this.getTargetItem( e
);
5050 if ( item
&& item
.isSelectable() ) {
5051 this.selecting
= item
;
5054 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
&& this.selecting
) {
5055 this.pressItem( null );
5056 this.chooseItem( this.selecting
);
5057 this.selecting
= null;
5060 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
5061 this.getElementDocument().removeEventListener( 'mousemove', this.onMouseMoveHandler
, true );
5067 * Handle mouse move events.
5070 * @param {MouseEvent} e Mouse move event
5072 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
5075 if ( !this.isDisabled() && this.pressed
) {
5076 item
= this.getTargetItem( e
);
5077 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
5078 this.pressItem( item
);
5079 this.selecting
= item
;
5085 * Handle mouse over events.
5088 * @param {jQuery.Event} e Mouse over event
5090 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
5092 if ( this.blockMouseOverEvents
) {
5095 if ( !this.isDisabled() ) {
5096 item
= this.getTargetItem( e
);
5097 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
5103 * Handle mouse leave events.
5106 * @param {jQuery.Event} e Mouse over event
5108 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
5109 if ( !this.isDisabled() ) {
5110 this.highlightItem( null );
5116 * Handle key down events.
5119 * @param {KeyboardEvent} e Key down event
5121 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
5124 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
5126 if ( !this.isDisabled() && this.isVisible() ) {
5127 switch ( e
.keyCode
) {
5128 case OO
.ui
.Keys
.ENTER
:
5129 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
5130 // Was only highlighted, now let's select it. No-op if already selected.
5131 this.chooseItem( currentItem
);
5136 case OO
.ui
.Keys
.LEFT
:
5137 this.clearKeyPressBuffer();
5138 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
5141 case OO
.ui
.Keys
.DOWN
:
5142 case OO
.ui
.Keys
.RIGHT
:
5143 this.clearKeyPressBuffer();
5144 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
5147 case OO
.ui
.Keys
.ESCAPE
:
5148 case OO
.ui
.Keys
.TAB
:
5149 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
5150 currentItem
.setHighlighted( false );
5152 this.unbindKeyDownListener();
5153 this.unbindKeyPressListener();
5154 // Don't prevent tabbing away / defocusing
5160 if ( nextItem
.constructor.static.highlightable
) {
5161 this.highlightItem( nextItem
);
5163 this.chooseItem( nextItem
);
5165 this.scrollItemIntoView( nextItem
);
5170 e
.stopPropagation();
5176 * Bind key down listener.
5180 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
5181 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler
, true );
5185 * Unbind key down listener.
5189 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
5190 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler
, true );
5194 * Scroll item into view, preventing spurious mouse highlight actions from happening.
5196 * @param {OO.ui.OptionWidget} item Item to scroll into view
5198 OO
.ui
.SelectWidget
.prototype.scrollItemIntoView = function ( item
) {
5200 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling
5201 // and around 100-150 ms after it is finished.
5202 this.blockMouseOverEvents
++;
5203 item
.scrollElementIntoView().done( function () {
5204 setTimeout( function () {
5205 widget
.blockMouseOverEvents
--;
5211 * Clear the key-press buffer
5215 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
5216 if ( this.keyPressBufferTimer
) {
5217 clearTimeout( this.keyPressBufferTimer
);
5218 this.keyPressBufferTimer
= null;
5220 this.keyPressBuffer
= '';
5224 * Handle key press events.
5227 * @param {KeyboardEvent} e Key press event
5229 OO
.ui
.SelectWidget
.prototype.onKeyPress = function ( e
) {
5230 var c
, filter
, item
;
5232 if ( !e
.charCode
) {
5233 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
5234 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
5239 if ( String
.fromCodePoint
) {
5240 c
= String
.fromCodePoint( e
.charCode
);
5242 c
= String
.fromCharCode( e
.charCode
);
5245 if ( this.keyPressBufferTimer
) {
5246 clearTimeout( this.keyPressBufferTimer
);
5248 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
5250 item
= this.getHighlightedItem() || this.getSelectedItem();
5252 if ( this.keyPressBuffer
=== c
) {
5253 // Common (if weird) special case: typing "xxxx" will cycle through all
5254 // the items beginning with "x".
5256 item
= this.getRelativeSelectableItem( item
, 1 );
5259 this.keyPressBuffer
+= c
;
5262 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
5263 if ( !item
|| !filter( item
) ) {
5264 item
= this.getRelativeSelectableItem( item
, 1, filter
);
5267 if ( item
.constructor.static.highlightable
) {
5268 this.highlightItem( item
);
5270 this.chooseItem( item
);
5272 this.scrollItemIntoView( item
);
5276 e
.stopPropagation();
5280 * Get a matcher for the specific string
5283 * @param {string} s String to match against items
5284 * @param {boolean} [exact=false] Only accept exact matches
5285 * @return {Function} function ( OO.ui.OptionItem ) => boolean
5287 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
, exact
) {
5290 if ( s
.normalize
) {
5293 s
= exact
? s
.trim() : s
.replace( /^\s+/, '' );
5294 re
= '^\\s*' + s
.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
5298 re
= new RegExp( re
, 'i' );
5299 return function ( item
) {
5300 var l
= item
.getLabel();
5301 if ( typeof l
!== 'string' ) {
5302 l
= item
.$label
.text();
5304 if ( l
.normalize
) {
5307 return re
.test( l
);
5312 * Bind key press listener.
5316 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
5317 this.getElementWindow().addEventListener( 'keypress', this.onKeyPressHandler
, true );
5321 * Unbind key down listener.
5323 * If you override this, be sure to call this.clearKeyPressBuffer() from your
5328 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
5329 this.getElementWindow().removeEventListener( 'keypress', this.onKeyPressHandler
, true );
5330 this.clearKeyPressBuffer();
5334 * Visibility change handler
5337 * @param {boolean} visible
5339 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
5341 this.clearKeyPressBuffer();
5346 * Get the closest item to a jQuery.Event.
5349 * @param {jQuery.Event} e
5350 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
5352 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
5353 return $( e
.target
).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
5357 * Get selected item.
5359 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
5361 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
5364 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5365 if ( this.items
[ i
].isSelected() ) {
5366 return this.items
[ i
];
5373 * Get highlighted item.
5375 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
5377 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
5380 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5381 if ( this.items
[ i
].isHighlighted() ) {
5382 return this.items
[ i
];
5389 * Toggle pressed state.
5391 * Press is a state that occurs when a user mouses down on an item, but
5392 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
5393 * until the user releases the mouse.
5395 * @param {boolean} pressed An option is being pressed
5397 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
5398 if ( pressed
=== undefined ) {
5399 pressed
= !this.pressed
;
5401 if ( pressed
!== this.pressed
) {
5403 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
5404 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
5405 this.pressed
= pressed
;
5410 * Highlight an option. If the `item` param is omitted, no options will be highlighted
5411 * and any existing highlight will be removed. The highlight is mutually exclusive.
5413 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
5417 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
5418 var i
, len
, highlighted
,
5421 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5422 highlighted
= this.items
[ i
] === item
;
5423 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
5424 this.items
[ i
].setHighlighted( highlighted
);
5429 this.emit( 'highlight', item
);
5436 * Fetch an item by its label.
5438 * @param {string} label Label of the item to select.
5439 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
5440 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
5442 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
5444 len
= this.items
.length
,
5445 filter
= this.getItemMatcher( label
, true );
5447 for ( i
= 0; i
< len
; i
++ ) {
5448 item
= this.items
[ i
];
5449 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
5456 filter
= this.getItemMatcher( label
, false );
5457 for ( i
= 0; i
< len
; i
++ ) {
5458 item
= this.items
[ i
];
5459 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
5475 * Programmatically select an option by its label. If the item does not exist,
5476 * all options will be deselected.
5478 * @param {string} [label] Label of the item to select.
5479 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
5483 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
5484 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
5485 if ( label
=== undefined || !itemFromLabel
) {
5486 return this.selectItem();
5488 return this.selectItem( itemFromLabel
);
5492 * Programmatically select an option by its data. If the `data` parameter is omitted,
5493 * or if the item does not exist, all options will be deselected.
5495 * @param {Object|string} [data] Value of the item to select, omit to deselect all
5499 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
5500 var itemFromData
= this.getItemFromData( data
);
5501 if ( data
=== undefined || !itemFromData
) {
5502 return this.selectItem();
5504 return this.selectItem( itemFromData
);
5508 * Programmatically select an option by its reference. If the `item` parameter is omitted,
5509 * all options will be deselected.
5511 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
5515 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
5516 var i
, len
, selected
,
5519 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5520 selected
= this.items
[ i
] === item
;
5521 if ( this.items
[ i
].isSelected() !== selected
) {
5522 this.items
[ i
].setSelected( selected
);
5527 this.emit( 'select', item
);
5536 * Press is a state that occurs when a user mouses down on an item, but has not
5537 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
5538 * releases the mouse.
5540 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
5544 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
5545 var i
, len
, pressed
,
5548 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5549 pressed
= this.items
[ i
] === item
;
5550 if ( this.items
[ i
].isPressed() !== pressed
) {
5551 this.items
[ i
].setPressed( pressed
);
5556 this.emit( 'press', item
);
5565 * Note that ‘choose’ should never be modified programmatically. A user can choose
5566 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
5567 * use the #selectItem method.
5569 * This method is identical to #selectItem, but may vary in subclasses that take additional action
5570 * when users choose an item with the keyboard or mouse.
5572 * @param {OO.ui.OptionWidget} item Item to choose
5576 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
5578 this.selectItem( item
);
5579 this.emit( 'choose', item
);
5586 * Get an option by its position relative to the specified item (or to the start of the option array,
5587 * if item is `null`). The direction in which to search through the option array is specified with a
5588 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
5589 * `null` if there are no options in the array.
5591 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
5592 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
5593 * @param {Function} filter Only consider items for which this function returns
5594 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
5595 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
5597 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
, filter
) {
5598 var currentIndex
, nextIndex
, i
,
5599 increase
= direction
> 0 ? 1 : -1,
5600 len
= this.items
.length
;
5602 if ( !$.isFunction( filter
) ) {
5603 filter
= OO
.ui
.SelectWidget
.static.passAllFilter
;
5606 if ( item
instanceof OO
.ui
.OptionWidget
) {
5607 currentIndex
= this.items
.indexOf( item
);
5608 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
5610 // If no item is selected and moving forward, start at the beginning.
5611 // If moving backward, start at the end.
5612 nextIndex
= direction
> 0 ? 0 : len
- 1;
5615 for ( i
= 0; i
< len
; i
++ ) {
5616 item
= this.items
[ nextIndex
];
5617 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
5620 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
5626 * Get the next selectable item or `null` if there are no selectable items.
5627 * Disabled options and menu-section markers and breaks are not selectable.
5629 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
5631 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
5634 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5635 item
= this.items
[ i
];
5636 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() ) {
5645 * Add an array of options to the select. Optionally, an index number can be used to
5646 * specify an insertion point.
5648 * @param {OO.ui.OptionWidget[]} items Items to add
5649 * @param {number} [index] Index to insert items after
5653 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
5655 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
5657 // Always provide an index, even if it was omitted
5658 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
5664 * Remove the specified array of options from the select. Options will be detached
5665 * from the DOM, not removed, so they can be reused later. To remove all options from
5666 * the select, you may wish to use the #clearItems method instead.
5668 * @param {OO.ui.OptionWidget[]} items Items to remove
5672 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
5675 // Deselect items being removed
5676 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
5678 if ( item
.isSelected() ) {
5679 this.selectItem( null );
5684 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
5686 this.emit( 'remove', items
);
5692 * Clear all options from the select. Options will be detached from the DOM, not removed,
5693 * so that they can be reused later. To remove a subset of options from the select, use
5694 * the #removeItems method.
5699 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
5700 var items
= this.items
.slice();
5703 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
5706 this.selectItem( null );
5708 this.emit( 'remove', items
);
5714 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
5715 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
5716 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
5717 * options. For more information about options and selects, please see the
5718 * [OOjs UI documentation on MediaWiki][1].
5721 * // Decorated options in a select widget
5722 * var select = new OO.ui.SelectWidget( {
5724 * new OO.ui.DecoratedOptionWidget( {
5726 * label: 'Option with icon',
5729 * new OO.ui.DecoratedOptionWidget( {
5731 * label: 'Option with indicator',
5736 * $( 'body' ).append( select.$element );
5738 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5741 * @extends OO.ui.OptionWidget
5742 * @mixins OO.ui.mixin.IconElement
5743 * @mixins OO.ui.mixin.IndicatorElement
5746 * @param {Object} [config] Configuration options
5748 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
5749 // Parent constructor
5750 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
5752 // Mixin constructors
5753 OO
.ui
.mixin
.IconElement
.call( this, config
);
5754 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
5758 .addClass( 'oo-ui-decoratedOptionWidget' )
5759 .prepend( this.$icon
)
5760 .append( this.$indicator
);
5765 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
5766 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
5767 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
5770 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
5771 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
5772 * the [OOjs UI documentation on MediaWiki] [1] for more information.
5774 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
5777 * @extends OO.ui.DecoratedOptionWidget
5780 * @param {Object} [config] Configuration options
5782 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
5783 // Configuration initialization
5784 config
= $.extend( { icon
: 'check' }, config
);
5786 // Parent constructor
5787 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
5791 .attr( 'role', 'menuitem' )
5792 .addClass( 'oo-ui-menuOptionWidget' );
5797 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
5799 /* Static Properties */
5801 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
5804 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
5805 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
5808 * var myDropdown = new OO.ui.DropdownWidget( {
5811 * new OO.ui.MenuSectionOptionWidget( {
5814 * new OO.ui.MenuOptionWidget( {
5816 * label: 'Welsh Corgi'
5818 * new OO.ui.MenuOptionWidget( {
5820 * label: 'Standard Poodle'
5822 * new OO.ui.MenuSectionOptionWidget( {
5825 * new OO.ui.MenuOptionWidget( {
5832 * $( 'body' ).append( myDropdown.$element );
5835 * @extends OO.ui.DecoratedOptionWidget
5838 * @param {Object} [config] Configuration options
5840 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
5841 // Parent constructor
5842 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
5845 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' );
5850 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
5852 /* Static Properties */
5854 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
5856 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
5859 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
5860 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
5861 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
5862 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
5863 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
5864 * and customized to be opened, closed, and displayed as needed.
5866 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
5867 * mouse outside the menu.
5869 * Menus also have support for keyboard interaction:
5871 * - Enter/Return key: choose and select a menu option
5872 * - Up-arrow key: highlight the previous menu option
5873 * - Down-arrow key: highlight the next menu option
5874 * - Esc key: hide the menu
5876 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
5877 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5880 * @extends OO.ui.SelectWidget
5881 * @mixins OO.ui.mixin.ClippableElement
5884 * @param {Object} [config] Configuration options
5885 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
5886 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
5887 * and {@link OO.ui.mixin.LookupElement LookupElement}
5888 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
5889 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiSelectWidget CapsuleMultiSelectWidget}
5890 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
5891 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
5892 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
5893 * that button, unless the button (or its parent widget) is passed in here.
5894 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
5895 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
5897 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
5898 // Configuration initialization
5899 config
= config
|| {};
5901 // Parent constructor
5902 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
5904 // Mixin constructors
5905 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
5908 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
5909 this.filterFromInput
= !!config
.filterFromInput
;
5910 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
5911 this.$widget
= config
.widget
? config
.widget
.$element
: null;
5912 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
5913 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
5917 .addClass( 'oo-ui-menuSelectWidget' )
5918 .attr( 'role', 'menu' );
5920 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
5921 // that reference properties not initialized at that time of parent class construction
5922 // TODO: Find a better way to handle post-constructor setup
5923 this.visible
= false;
5924 this.$element
.addClass( 'oo-ui-element-hidden' );
5929 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
5930 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
5935 * Handles document mouse down events.
5938 * @param {MouseEvent} e Mouse down event
5940 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
5942 !OO
.ui
.contains( this.$element
[ 0 ], e
.target
, true ) &&
5943 ( !this.$widget
|| !OO
.ui
.contains( this.$widget
[ 0 ], e
.target
, true ) )
5945 this.toggle( false );
5952 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
5953 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
5955 if ( !this.isDisabled() && this.isVisible() ) {
5956 switch ( e
.keyCode
) {
5957 case OO
.ui
.Keys
.LEFT
:
5958 case OO
.ui
.Keys
.RIGHT
:
5959 // Do nothing if a text field is associated, arrow keys will be handled natively
5960 if ( !this.$input
) {
5961 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
5964 case OO
.ui
.Keys
.ESCAPE
:
5965 case OO
.ui
.Keys
.TAB
:
5966 if ( currentItem
) {
5967 currentItem
.setHighlighted( false );
5969 this.toggle( false );
5970 // Don't prevent tabbing away, prevent defocusing
5971 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
5973 e
.stopPropagation();
5977 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
5984 * Update menu item visibility after input changes.
5988 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
5990 len
= this.items
.length
,
5991 showAll
= !this.isVisible(),
5992 filter
= showAll
? null : this.getItemMatcher( this.$input
.val() );
5994 for ( i
= 0; i
< len
; i
++ ) {
5995 item
= this.items
[ i
];
5996 if ( item
instanceof OO
.ui
.OptionWidget
) {
5997 item
.toggle( showAll
|| filter( item
) );
6001 // Reevaluate clipping
6008 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
6009 if ( this.$input
) {
6010 this.$input
.on( 'keydown', this.onKeyDownHandler
);
6012 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyDownListener
.call( this );
6019 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
6020 if ( this.$input
) {
6021 this.$input
.off( 'keydown', this.onKeyDownHandler
);
6023 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyDownListener
.call( this );
6030 OO
.ui
.MenuSelectWidget
.prototype.bindKeyPressListener = function () {
6031 if ( this.$input
) {
6032 if ( this.filterFromInput
) {
6033 this.$input
.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
6036 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyPressListener
.call( this );
6043 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyPressListener = function () {
6044 if ( this.$input
) {
6045 if ( this.filterFromInput
) {
6046 this.$input
.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
6047 this.updateItemVisibility();
6050 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyPressListener
.call( this );
6057 * When a user chooses an item, the menu is closed.
6059 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
6060 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
6062 * @param {OO.ui.OptionWidget} item Item to choose
6065 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
6066 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
6067 this.toggle( false );
6074 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
6076 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
6078 // Reevaluate clipping
6087 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
6089 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
6091 // Reevaluate clipping
6100 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
6102 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
6104 // Reevaluate clipping
6113 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
6116 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
6117 change
= visible
!== this.isVisible();
6120 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
6124 this.bindKeyDownListener();
6125 this.bindKeyPressListener();
6127 this.toggleClipping( true );
6129 if ( this.getSelectedItem() ) {
6130 this.getSelectedItem().scrollElementIntoView( { duration
: 0 } );
6134 if ( this.autoHide
) {
6135 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
6138 this.unbindKeyDownListener();
6139 this.unbindKeyPressListener();
6140 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
6141 this.toggleClipping( false );
6149 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
6150 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
6151 * users can interact with it.
6153 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
6154 * OO.ui.DropdownInputWidget instead.
6157 * // Example: A DropdownWidget with a menu that contains three options
6158 * var dropDown = new OO.ui.DropdownWidget( {
6159 * label: 'Dropdown menu: Select a menu option',
6162 * new OO.ui.MenuOptionWidget( {
6166 * new OO.ui.MenuOptionWidget( {
6170 * new OO.ui.MenuOptionWidget( {
6178 * $( 'body' ).append( dropDown.$element );
6180 * dropDown.getMenu().selectItemByData( 'b' );
6182 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
6184 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
6186 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
6189 * @extends OO.ui.Widget
6190 * @mixins OO.ui.mixin.IconElement
6191 * @mixins OO.ui.mixin.IndicatorElement
6192 * @mixins OO.ui.mixin.LabelElement
6193 * @mixins OO.ui.mixin.TitledElement
6194 * @mixins OO.ui.mixin.TabIndexedElement
6197 * @param {Object} [config] Configuration options
6198 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
6199 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
6200 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
6201 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
6203 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
6204 // Configuration initialization
6205 config
= $.extend( { indicator
: 'down' }, config
);
6207 // Parent constructor
6208 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
6210 // Properties (must be set before TabIndexedElement constructor call)
6211 this.$handle
= this.$( '<span>' );
6212 this.$overlay
= config
.$overlay
|| this.$element
;
6214 // Mixin constructors
6215 OO
.ui
.mixin
.IconElement
.call( this, config
);
6216 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
6217 OO
.ui
.mixin
.LabelElement
.call( this, config
);
6218 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
6219 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
6222 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend( {
6224 $container
: this.$element
6229 click
: this.onClick
.bind( this ),
6230 keydown
: this.onKeyDown
.bind( this )
6232 this.menu
.connect( this, { select
: 'onMenuSelect' } );
6236 .addClass( 'oo-ui-dropdownWidget-handle' )
6237 .append( this.$icon
, this.$label
, this.$indicator
);
6239 .addClass( 'oo-ui-dropdownWidget' )
6240 .append( this.$handle
);
6241 this.$overlay
.append( this.menu
.$element
);
6246 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
6247 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
6248 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
6249 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
6250 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
6251 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
6258 * @return {OO.ui.MenuSelectWidget} Menu of widget
6260 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
6265 * Handles menu select events.
6268 * @param {OO.ui.MenuOptionWidget} item Selected menu item
6270 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
6274 this.setLabel( null );
6278 selectedLabel
= item
.getLabel();
6280 // If the label is a DOM element, clone it, because setLabel will append() it
6281 if ( selectedLabel
instanceof jQuery
) {
6282 selectedLabel
= selectedLabel
.clone();
6285 this.setLabel( selectedLabel
);
6289 * Handle mouse click events.
6292 * @param {jQuery.Event} e Mouse click event
6294 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
6295 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
6302 * Handle key down events.
6305 * @param {jQuery.Event} e Key down event
6307 OO
.ui
.DropdownWidget
.prototype.onKeyDown = function ( e
) {
6309 !this.isDisabled() &&
6311 e
.which
=== OO
.ui
.Keys
.ENTER
||
6313 !this.menu
.isVisible() &&
6315 e
.which
=== OO
.ui
.Keys
.SPACE
||
6316 e
.which
=== OO
.ui
.Keys
.UP
||
6317 e
.which
=== OO
.ui
.Keys
.DOWN
6328 * RadioOptionWidget is an option widget that looks like a radio button.
6329 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
6330 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6332 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
6335 * @extends OO.ui.OptionWidget
6338 * @param {Object} [config] Configuration options
6340 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
6341 // Configuration initialization
6342 config
= config
|| {};
6344 // Properties (must be done before parent constructor which calls #setDisabled)
6345 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
6347 // Parent constructor
6348 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
6351 this.radio
.$input
.on( 'focus', this.onInputFocus
.bind( this ) );
6354 // Remove implicit role, we're handling it ourselves
6355 this.radio
.$input
.attr( 'role', 'presentation' );
6357 .addClass( 'oo-ui-radioOptionWidget' )
6358 .attr( 'role', 'radio' )
6359 .attr( 'aria-checked', 'false' )
6360 .removeAttr( 'aria-selected' )
6361 .prepend( this.radio
.$element
);
6366 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
6368 /* Static Properties */
6370 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
6372 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
6374 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
6376 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
6381 * @param {jQuery.Event} e Focus event
6384 OO
.ui
.RadioOptionWidget
.prototype.onInputFocus = function () {
6385 this.radio
.$input
.blur();
6386 this.$element
.parent().focus();
6392 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
6393 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
6395 this.radio
.setSelected( state
);
6397 .attr( 'aria-checked', state
.toString() )
6398 .removeAttr( 'aria-selected' );
6406 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
6407 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
6409 this.radio
.setDisabled( this.isDisabled() );
6415 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
6416 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
6417 * an interface for adding, removing and selecting options.
6418 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
6420 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
6421 * OO.ui.RadioSelectInputWidget instead.
6424 * // A RadioSelectWidget with RadioOptions.
6425 * var option1 = new OO.ui.RadioOptionWidget( {
6427 * label: 'Selected radio option'
6430 * var option2 = new OO.ui.RadioOptionWidget( {
6432 * label: 'Unselected radio option'
6435 * var radioSelect=new OO.ui.RadioSelectWidget( {
6436 * items: [ option1, option2 ]
6439 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
6440 * radioSelect.selectItem( option1 );
6442 * $( 'body' ).append( radioSelect.$element );
6444 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6448 * @extends OO.ui.SelectWidget
6449 * @mixins OO.ui.mixin.TabIndexedElement
6452 * @param {Object} [config] Configuration options
6454 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
6455 // Parent constructor
6456 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
6458 // Mixin constructors
6459 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
6463 focus
: this.bindKeyDownListener
.bind( this ),
6464 blur
: this.unbindKeyDownListener
.bind( this )
6469 .addClass( 'oo-ui-radioSelectWidget' )
6470 .attr( 'role', 'radiogroup' );
6475 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
6476 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
6479 * Element that will stick under a specified container, even when it is inserted elsewhere in the
6480 * document (for example, in a OO.ui.Window's $overlay).
6482 * The elements's position is automatically calculated and maintained when window is resized or the
6483 * page is scrolled. If you reposition the container manually, you have to call #position to make
6484 * sure the element is still placed correctly.
6486 * As positioning is only possible when both the element and the container are attached to the DOM
6487 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
6488 * the #toggle method to display a floating popup, for example.
6494 * @param {Object} [config] Configuration options
6495 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
6496 * @cfg {jQuery} [$floatableContainer] Node to position below
6498 OO
.ui
.mixin
.FloatableElement
= function OoUiMixinFloatableElement( config
) {
6499 // Configuration initialization
6500 config
= config
|| {};
6503 this.$floatable
= null;
6504 this.$floatableContainer
= null;
6505 this.$floatableWindow
= null;
6506 this.$floatableClosestScrollable
= null;
6507 this.onFloatableScrollHandler
= this.position
.bind( this );
6508 this.onFloatableWindowResizeHandler
= this.position
.bind( this );
6511 this.setFloatableContainer( config
.$floatableContainer
);
6512 this.setFloatableElement( config
.$floatable
|| this.$element
);
6518 * Set floatable element.
6520 * If an element is already set, it will be cleaned up before setting up the new element.
6522 * @param {jQuery} $floatable Element to make floatable
6524 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableElement = function ( $floatable
) {
6525 if ( this.$floatable
) {
6526 this.$floatable
.removeClass( 'oo-ui-floatableElement-floatable' );
6527 this.$floatable
.css( { left
: '', top
: '' } );
6530 this.$floatable
= $floatable
.addClass( 'oo-ui-floatableElement-floatable' );
6535 * Set floatable container.
6537 * The element will be always positioned under the specified container.
6539 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
6541 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableContainer = function ( $floatableContainer
) {
6542 this.$floatableContainer
= $floatableContainer
;
6543 if ( this.$floatable
) {
6549 * Toggle positioning.
6551 * Do not turn positioning on until after the element is attached to the DOM and visible.
6553 * @param {boolean} [positioning] Enable positioning, omit to toggle
6556 OO
.ui
.mixin
.FloatableElement
.prototype.togglePositioning = function ( positioning
) {
6557 var closestScrollableOfContainer
, closestScrollableOfFloatable
;
6559 positioning
= positioning
=== undefined ? !this.positioning
: !!positioning
;
6561 if ( this.positioning
!== positioning
) {
6562 this.positioning
= positioning
;
6564 closestScrollableOfContainer
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatableContainer
[ 0 ] );
6565 closestScrollableOfFloatable
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatable
[ 0 ] );
6566 if ( closestScrollableOfContainer
!== closestScrollableOfFloatable
) {
6567 // If the scrollable is the root, we have to listen to scroll events
6568 // on the window because of browser inconsistencies (or do we? someone should verify this)
6569 if ( $( closestScrollableOfContainer
).is( 'html, body' ) ) {
6570 closestScrollableOfContainer
= OO
.ui
.Element
.static.getWindow( closestScrollableOfContainer
);
6574 if ( positioning
) {
6575 this.$floatableWindow
= $( this.getElementWindow() );
6576 this.$floatableWindow
.on( 'resize', this.onFloatableWindowResizeHandler
);
6578 if ( closestScrollableOfContainer
!== closestScrollableOfFloatable
) {
6579 this.$floatableClosestScrollable
= $( closestScrollableOfContainer
);
6580 this.$floatableClosestScrollable
.on( 'scroll', this.onFloatableScrollHandler
);
6583 // Initial position after visible
6586 if ( this.$floatableWindow
) {
6587 this.$floatableWindow
.off( 'resize', this.onFloatableWindowResizeHandler
);
6588 this.$floatableWindow
= null;
6591 if ( this.$floatableClosestScrollable
) {
6592 this.$floatableClosestScrollable
.off( 'scroll', this.onFloatableScrollHandler
);
6593 this.$floatableClosestScrollable
= null;
6596 this.$floatable
.css( { left
: '', top
: '' } );
6604 * Position the floatable below its container.
6606 * This should only be done when both of them are attached to the DOM and visible.
6610 OO
.ui
.mixin
.FloatableElement
.prototype.position = function () {
6613 if ( !this.positioning
) {
6617 pos
= OO
.ui
.Element
.static.getRelativePosition( this.$floatableContainer
, this.$floatable
.offsetParent() );
6619 // Position under container
6620 pos
.top
+= this.$floatableContainer
.height();
6621 this.$floatable
.css( pos
);
6623 // We updated the position, so re-evaluate the clipping state.
6624 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
6625 // will not notice the need to update itself.)
6626 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
6627 // it not listen to the right events in the right places?
6636 * FloatingMenuSelectWidget is a menu that will stick under a specified
6637 * container, even when it is inserted elsewhere in the document (for example,
6638 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
6639 * menu from being clipped too aggresively.
6641 * The menu's position is automatically calculated and maintained when the menu
6642 * is toggled or the window is resized.
6644 * See OO.ui.ComboBoxInputWidget for an example of a widget that uses this class.
6647 * @extends OO.ui.MenuSelectWidget
6648 * @mixins OO.ui.mixin.FloatableElement
6651 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
6652 * Deprecated, omit this parameter and specify `$container` instead.
6653 * @param {Object} [config] Configuration options
6654 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
6656 OO
.ui
.FloatingMenuSelectWidget
= function OoUiFloatingMenuSelectWidget( inputWidget
, config
) {
6657 // Allow 'inputWidget' parameter and config for backwards compatibility
6658 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
6659 config
= inputWidget
;
6660 inputWidget
= config
.inputWidget
;
6663 // Configuration initialization
6664 config
= config
|| {};
6666 // Parent constructor
6667 OO
.ui
.FloatingMenuSelectWidget
.parent
.call( this, config
);
6669 // Properties (must be set before mixin constructors)
6670 this.inputWidget
= inputWidget
; // For backwards compatibility
6671 this.$container
= config
.$container
|| this.inputWidget
.$element
;
6673 // Mixins constructors
6674 OO
.ui
.mixin
.FloatableElement
.call( this, $.extend( {}, config
, { $floatableContainer
: this.$container
} ) );
6677 this.$element
.addClass( 'oo-ui-floatingMenuSelectWidget' );
6678 // For backwards compatibility
6679 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
6684 OO
.inheritClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
6685 OO
.mixinClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.mixin
.FloatableElement
);
6687 // For backwards compatibility
6688 OO
.ui
.TextInputMenuSelectWidget
= OO
.ui
.FloatingMenuSelectWidget
;
6695 OO
.ui
.FloatingMenuSelectWidget
.prototype.toggle = function ( visible
) {
6697 visible
= visible
=== undefined ? !this.isVisible() : !!visible
;
6698 change
= visible
!== this.isVisible();
6700 if ( change
&& visible
) {
6701 // Make sure the width is set before the parent method runs.
6702 this.setIdealSize( this.$container
.width() );
6706 // This will call this.clip(), which is nonsensical since we're not positioned yet...
6707 OO
.ui
.FloatingMenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
6710 this.togglePositioning( this.isVisible() );
6717 * InputWidget is the base class for all input widgets, which
6718 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
6719 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
6720 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
6722 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
6726 * @extends OO.ui.Widget
6727 * @mixins OO.ui.mixin.FlaggedElement
6728 * @mixins OO.ui.mixin.TabIndexedElement
6729 * @mixins OO.ui.mixin.TitledElement
6730 * @mixins OO.ui.mixin.AccessKeyedElement
6733 * @param {Object} [config] Configuration options
6734 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
6735 * @cfg {string} [value=''] The value of the input.
6736 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
6737 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
6738 * before it is accepted.
6740 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
6741 // Configuration initialization
6742 config
= config
|| {};
6744 // Parent constructor
6745 OO
.ui
.InputWidget
.parent
.call( this, config
);
6748 this.$input
= this.getInputElement( config
);
6750 this.inputFilter
= config
.inputFilter
;
6752 // Mixin constructors
6753 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
6754 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
6755 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
6756 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$input
} ) );
6759 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
6763 .addClass( 'oo-ui-inputWidget-input' )
6764 .attr( 'name', config
.name
)
6765 .prop( 'disabled', this.isDisabled() );
6767 .addClass( 'oo-ui-inputWidget' )
6768 .append( this.$input
);
6769 this.setValue( config
.value
);
6771 this.setDir( config
.dir
);
6777 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
6778 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
6779 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
6780 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
6781 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
6783 /* Static Properties */
6785 OO
.ui
.InputWidget
.static.supportsSimpleLabel
= true;
6787 /* Static Methods */
6792 OO
.ui
.InputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
6793 config
= OO
.ui
.InputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
6794 // Reusing $input lets browsers preserve inputted values across page reloads (T114134)
6795 config
.$input
= $( node
).find( '.oo-ui-inputWidget-input' );
6802 OO
.ui
.InputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
6803 var state
= OO
.ui
.InputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
6804 state
.value
= config
.$input
.val();
6805 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
6806 state
.focus
= config
.$input
.is( ':focus' );
6815 * A change event is emitted when the value of the input changes.
6817 * @param {string} value
6823 * Get input element.
6825 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
6826 * different circumstances. The element must have a `value` property (like form elements).
6829 * @param {Object} config Configuration options
6830 * @return {jQuery} Input element
6832 OO
.ui
.InputWidget
.prototype.getInputElement = function ( config
) {
6833 // See #reusePreInfuseDOM about config.$input
6834 return config
.$input
|| $( '<input>' );
6838 * Handle potentially value-changing events.
6841 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
6843 OO
.ui
.InputWidget
.prototype.onEdit = function () {
6845 if ( !this.isDisabled() ) {
6846 // Allow the stack to clear so the value will be updated
6847 setTimeout( function () {
6848 widget
.setValue( widget
.$input
.val() );
6854 * Get the value of the input.
6856 * @return {string} Input value
6858 OO
.ui
.InputWidget
.prototype.getValue = function () {
6859 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
6860 // it, and we won't know unless they're kind enough to trigger a 'change' event.
6861 var value
= this.$input
.val();
6862 if ( this.value
!== value
) {
6863 this.setValue( value
);
6869 * Set the directionality of the input, either RTL (right-to-left) or LTR (left-to-right).
6871 * @deprecated since v0.13.1; use #setDir directly
6872 * @param {boolean} isRTL Directionality is right-to-left
6875 OO
.ui
.InputWidget
.prototype.setRTL = function ( isRTL
) {
6876 this.setDir( isRTL
? 'rtl' : 'ltr' );
6881 * Set the directionality of the input.
6883 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
6886 OO
.ui
.InputWidget
.prototype.setDir = function ( dir
) {
6887 this.$input
.prop( 'dir', dir
);
6892 * Set the value of the input.
6894 * @param {string} value New value
6898 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
6899 value
= this.cleanUpValue( value
);
6900 // Update the DOM if it has changed. Note that with cleanUpValue, it
6901 // is possible for the DOM value to change without this.value changing.
6902 if ( this.$input
.val() !== value
) {
6903 this.$input
.val( value
);
6905 if ( this.value
!== value
) {
6907 this.emit( 'change', this.value
);
6913 * Clean up incoming value.
6915 * Ensures value is a string, and converts undefined and null to empty string.
6918 * @param {string} value Original value
6919 * @return {string} Cleaned up value
6921 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
6922 if ( value
=== undefined || value
=== null ) {
6924 } else if ( this.inputFilter
) {
6925 return this.inputFilter( String( value
) );
6927 return String( value
);
6932 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
6933 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
6936 OO
.ui
.InputWidget
.prototype.simulateLabelClick = function () {
6937 if ( !this.isDisabled() ) {
6938 if ( this.$input
.is( ':checkbox, :radio' ) ) {
6939 this.$input
.click();
6941 if ( this.$input
.is( ':input' ) ) {
6942 this.$input
[ 0 ].focus();
6950 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
6951 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
6952 if ( this.$input
) {
6953 this.$input
.prop( 'disabled', this.isDisabled() );
6963 OO
.ui
.InputWidget
.prototype.focus = function () {
6964 this.$input
[ 0 ].focus();
6973 OO
.ui
.InputWidget
.prototype.blur = function () {
6974 this.$input
[ 0 ].blur();
6981 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
6982 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
6983 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
6984 this.setValue( state
.value
);
6986 if ( state
.focus
) {
6992 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
6993 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
6994 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
6995 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
6996 * [OOjs UI documentation on MediaWiki] [1] for more information.
6999 * // A ButtonInputWidget rendered as an HTML button, the default.
7000 * var button = new OO.ui.ButtonInputWidget( {
7001 * label: 'Input button',
7005 * $( 'body' ).append( button.$element );
7007 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
7010 * @extends OO.ui.InputWidget
7011 * @mixins OO.ui.mixin.ButtonElement
7012 * @mixins OO.ui.mixin.IconElement
7013 * @mixins OO.ui.mixin.IndicatorElement
7014 * @mixins OO.ui.mixin.LabelElement
7015 * @mixins OO.ui.mixin.TitledElement
7018 * @param {Object} [config] Configuration options
7019 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
7020 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
7021 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
7022 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
7023 * be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
7025 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
7026 // Configuration initialization
7027 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
7029 // Properties (must be set before parent constructor, which calls #setValue)
7030 this.useInputTag
= config
.useInputTag
;
7032 // Parent constructor
7033 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
7035 // Mixin constructors
7036 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
7037 OO
.ui
.mixin
.IconElement
.call( this, config
);
7038 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
7039 OO
.ui
.mixin
.LabelElement
.call( this, config
);
7040 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
7043 if ( !config
.useInputTag
) {
7044 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
7046 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
7051 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
7052 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
7053 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
7054 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
7055 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
7056 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
7058 /* Static Properties */
7061 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
7062 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
7064 OO
.ui
.ButtonInputWidget
.static.supportsSimpleLabel
= false;
7072 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
7074 // See InputWidget#reusePreInfuseDOM about config.$input
7075 if ( config
.$input
) {
7076 return config
.$input
.empty();
7078 type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ? config
.type
: 'button';
7079 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
7085 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
7087 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
7088 * text, or `null` for no label
7091 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
7092 OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
7094 if ( this.useInputTag
) {
7095 if ( typeof label
=== 'function' ) {
7096 label
= OO
.ui
.resolveMsg( label
);
7098 if ( label
instanceof jQuery
) {
7099 label
= label
.text();
7104 this.$input
.val( label
);
7111 * Set the value of the input.
7113 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
7114 * they do not support {@link #value values}.
7116 * @param {string} value New value
7119 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
7120 if ( !this.useInputTag
) {
7121 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
7127 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
7128 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
7129 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
7130 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
7132 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
7135 * // An example of selected, unselected, and disabled checkbox inputs
7136 * var checkbox1=new OO.ui.CheckboxInputWidget( {
7140 * var checkbox2=new OO.ui.CheckboxInputWidget( {
7143 * var checkbox3=new OO.ui.CheckboxInputWidget( {
7147 * // Create a fieldset layout with fields for each checkbox.
7148 * var fieldset = new OO.ui.FieldsetLayout( {
7149 * label: 'Checkboxes'
7151 * fieldset.addItems( [
7152 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
7153 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
7154 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
7156 * $( 'body' ).append( fieldset.$element );
7158 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7161 * @extends OO.ui.InputWidget
7164 * @param {Object} [config] Configuration options
7165 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
7167 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
7168 // Configuration initialization
7169 config
= config
|| {};
7171 // Parent constructor
7172 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
7176 .addClass( 'oo-ui-checkboxInputWidget' )
7177 // Required for pretty styling in MediaWiki theme
7178 .append( $( '<span>' ) );
7179 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
7184 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
7186 /* Static Methods */
7191 OO
.ui
.CheckboxInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
7192 var state
= OO
.ui
.CheckboxInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
7193 state
.checked
= config
.$input
.prop( 'checked' );
7203 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
7204 return $( '<input>' ).attr( 'type', 'checkbox' );
7210 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
7212 if ( !this.isDisabled() ) {
7213 // Allow the stack to clear so the value will be updated
7214 setTimeout( function () {
7215 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
7221 * Set selection state of this checkbox.
7223 * @param {boolean} state `true` for selected
7226 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
7228 if ( this.selected
!== state
) {
7229 this.selected
= state
;
7230 this.$input
.prop( 'checked', this.selected
);
7231 this.emit( 'change', this.selected
);
7237 * Check if this checkbox is selected.
7239 * @return {boolean} Checkbox is selected
7241 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
7242 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
7243 // it, and we won't know unless they're kind enough to trigger a 'change' event.
7244 var selected
= this.$input
.prop( 'checked' );
7245 if ( this.selected
!== selected
) {
7246 this.setSelected( selected
);
7248 return this.selected
;
7254 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
7255 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
7256 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
7257 this.setSelected( state
.checked
);
7262 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
7263 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
7264 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
7265 * more information about input widgets.
7267 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
7268 * are no options. If no `value` configuration option is provided, the first option is selected.
7269 * If you need a state representing no value (no option being selected), use a DropdownWidget.
7271 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
7274 * // Example: A DropdownInputWidget with three options
7275 * var dropdownInput = new OO.ui.DropdownInputWidget( {
7277 * { data: 'a', label: 'First' },
7278 * { data: 'b', label: 'Second'},
7279 * { data: 'c', label: 'Third' }
7282 * $( 'body' ).append( dropdownInput.$element );
7284 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7287 * @extends OO.ui.InputWidget
7288 * @mixins OO.ui.mixin.TitledElement
7291 * @param {Object} [config] Configuration options
7292 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
7293 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
7295 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
7296 // Configuration initialization
7297 config
= config
|| {};
7299 // Properties (must be done before parent constructor which calls #setDisabled)
7300 this.dropdownWidget
= new OO
.ui
.DropdownWidget( config
.dropdown
);
7302 // Parent constructor
7303 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
7305 // Mixin constructors
7306 OO
.ui
.mixin
.TitledElement
.call( this, config
);
7309 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
7312 this.setOptions( config
.options
|| [] );
7314 .addClass( 'oo-ui-dropdownInputWidget' )
7315 .append( this.dropdownWidget
.$element
);
7320 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
7321 OO
.mixinClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.mixin
.TitledElement
);
7329 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function ( config
) {
7330 // See InputWidget#reusePreInfuseDOM about config.$input
7331 if ( config
.$input
) {
7332 return config
.$input
.addClass( 'oo-ui-element-hidden' );
7334 return $( '<input>' ).attr( 'type', 'hidden' );
7338 * Handles menu select events.
7341 * @param {OO.ui.MenuOptionWidget} item Selected menu item
7343 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
7344 this.setValue( item
.getData() );
7350 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
7351 value
= this.cleanUpValue( value
);
7352 this.dropdownWidget
.getMenu().selectItemByData( value
);
7353 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
7360 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
7361 this.dropdownWidget
.setDisabled( state
);
7362 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
7367 * Set the options available for this input.
7369 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
7372 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
7374 value
= this.getValue(),
7377 // Rebuild the dropdown menu
7378 this.dropdownWidget
.getMenu()
7380 .addItems( options
.map( function ( opt
) {
7381 var optValue
= widget
.cleanUpValue( opt
.data
);
7382 return new OO
.ui
.MenuOptionWidget( {
7384 label
: opt
.label
!== undefined ? opt
.label
: optValue
7388 // Restore the previous value, or reset to something sensible
7389 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
7390 // Previous value is still available, ensure consistency with the dropdown
7391 this.setValue( value
);
7393 // No longer valid, reset
7394 if ( options
.length
) {
7395 this.setValue( options
[ 0 ].data
);
7405 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
7406 this.dropdownWidget
.getMenu().toggle( true );
7413 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
7414 this.dropdownWidget
.getMenu().toggle( false );
7419 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
7420 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
7421 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
7422 * please see the [OOjs UI documentation on MediaWiki][1].
7424 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
7427 * // An example of selected, unselected, and disabled radio inputs
7428 * var radio1 = new OO.ui.RadioInputWidget( {
7432 * var radio2 = new OO.ui.RadioInputWidget( {
7435 * var radio3 = new OO.ui.RadioInputWidget( {
7439 * // Create a fieldset layout with fields for each radio button.
7440 * var fieldset = new OO.ui.FieldsetLayout( {
7441 * label: 'Radio inputs'
7443 * fieldset.addItems( [
7444 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
7445 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
7446 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
7448 * $( 'body' ).append( fieldset.$element );
7450 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7453 * @extends OO.ui.InputWidget
7456 * @param {Object} [config] Configuration options
7457 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
7459 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
7460 // Configuration initialization
7461 config
= config
|| {};
7463 // Parent constructor
7464 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
7468 .addClass( 'oo-ui-radioInputWidget' )
7469 // Required for pretty styling in MediaWiki theme
7470 .append( $( '<span>' ) );
7471 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
7476 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
7478 /* Static Methods */
7483 OO
.ui
.RadioInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
7484 var state
= OO
.ui
.RadioInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
7485 state
.checked
= config
.$input
.prop( 'checked' );
7495 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
7496 return $( '<input>' ).attr( 'type', 'radio' );
7502 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
7503 // RadioInputWidget doesn't track its state.
7507 * Set selection state of this radio button.
7509 * @param {boolean} state `true` for selected
7512 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
7513 // RadioInputWidget doesn't track its state.
7514 this.$input
.prop( 'checked', state
);
7519 * Check if this radio button is selected.
7521 * @return {boolean} Radio is selected
7523 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
7524 return this.$input
.prop( 'checked' );
7530 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
7531 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
7532 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
7533 this.setSelected( state
.checked
);
7538 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
7539 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
7540 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
7541 * more information about input widgets.
7543 * This and OO.ui.DropdownInputWidget support the same configuration options.
7546 * // Example: A RadioSelectInputWidget with three options
7547 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
7549 * { data: 'a', label: 'First' },
7550 * { data: 'b', label: 'Second'},
7551 * { data: 'c', label: 'Third' }
7554 * $( 'body' ).append( radioSelectInput.$element );
7556 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7559 * @extends OO.ui.InputWidget
7562 * @param {Object} [config] Configuration options
7563 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
7565 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
7566 // Configuration initialization
7567 config
= config
|| {};
7569 // Properties (must be done before parent constructor which calls #setDisabled)
7570 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
7572 // Parent constructor
7573 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
7576 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
7579 this.setOptions( config
.options
|| [] );
7581 .addClass( 'oo-ui-radioSelectInputWidget' )
7582 .append( this.radioSelectWidget
.$element
);
7587 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
7589 /* Static Properties */
7591 OO
.ui
.RadioSelectInputWidget
.static.supportsSimpleLabel
= false;
7593 /* Static Methods */
7598 OO
.ui
.RadioSelectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
7599 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
7600 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
7610 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
7611 return $( '<input>' ).attr( 'type', 'hidden' );
7615 * Handles menu select events.
7618 * @param {OO.ui.RadioOptionWidget} item Selected menu item
7620 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
7621 this.setValue( item
.getData() );
7627 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
7628 value
= this.cleanUpValue( value
);
7629 this.radioSelectWidget
.selectItemByData( value
);
7630 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
7637 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
7638 this.radioSelectWidget
.setDisabled( state
);
7639 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
7644 * Set the options available for this input.
7646 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
7649 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
7651 value
= this.getValue(),
7654 // Rebuild the radioSelect menu
7655 this.radioSelectWidget
7657 .addItems( options
.map( function ( opt
) {
7658 var optValue
= widget
.cleanUpValue( opt
.data
);
7659 return new OO
.ui
.RadioOptionWidget( {
7661 label
: opt
.label
!== undefined ? opt
.label
: optValue
7665 // Restore the previous value, or reset to something sensible
7666 if ( this.radioSelectWidget
.getItemFromData( value
) ) {
7667 // Previous value is still available, ensure consistency with the radioSelect
7668 this.setValue( value
);
7670 // No longer valid, reset
7671 if ( options
.length
) {
7672 this.setValue( options
[ 0 ].data
);
7680 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
7681 * size of the field as well as its presentation. In addition, these widgets can be configured
7682 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
7683 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
7684 * which modifies incoming values rather than validating them.
7685 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
7687 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
7690 * // Example of a text input widget
7691 * var textInput = new OO.ui.TextInputWidget( {
7692 * value: 'Text input'
7694 * $( 'body' ).append( textInput.$element );
7696 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7699 * @extends OO.ui.InputWidget
7700 * @mixins OO.ui.mixin.IconElement
7701 * @mixins OO.ui.mixin.IndicatorElement
7702 * @mixins OO.ui.mixin.PendingElement
7703 * @mixins OO.ui.mixin.LabelElement
7706 * @param {Object} [config] Configuration options
7707 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
7708 * 'email', 'url' or 'date'. Ignored if `multiline` is true.
7710 * Some values of `type` result in additional behaviors:
7712 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
7713 * empties the text field
7714 * @cfg {string} [placeholder] Placeholder text
7715 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
7716 * instruct the browser to focus this widget.
7717 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
7718 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
7719 * @cfg {boolean} [multiline=false] Allow multiple lines of text
7720 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
7721 * specifies minimum number of rows to display.
7722 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
7723 * Use the #maxRows config to specify a maximum number of displayed rows.
7724 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
7725 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
7726 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
7727 * the value or placeholder text: `'before'` or `'after'`
7728 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
7729 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
7730 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
7731 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
7732 * (the value must contain only numbers); when RegExp, a regular expression that must match the
7733 * value for it to be considered valid; when Function, a function receiving the value as parameter
7734 * that must return true, or promise resolving to true, for it to be considered valid.
7736 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
7737 // Configuration initialization
7738 config
= $.extend( {
7740 labelPosition
: 'after'
7742 if ( config
.type
=== 'search' ) {
7743 if ( config
.icon
=== undefined ) {
7744 config
.icon
= 'search';
7746 // indicator: 'clear' is set dynamically later, depending on value
7748 if ( config
.required
) {
7749 if ( config
.indicator
=== undefined ) {
7750 config
.indicator
= 'required';
7754 // Parent constructor
7755 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
7757 // Mixin constructors
7758 OO
.ui
.mixin
.IconElement
.call( this, config
);
7759 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
7760 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
7761 OO
.ui
.mixin
.LabelElement
.call( this, config
);
7764 this.type
= this.getSaneType( config
);
7765 this.readOnly
= false;
7766 this.multiline
= !!config
.multiline
;
7767 this.autosize
= !!config
.autosize
;
7768 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
7769 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
7770 this.validate
= null;
7771 this.styleHeight
= null;
7772 this.scrollWidth
= null;
7774 // Clone for resizing
7775 if ( this.autosize
) {
7776 this.$clone
= this.$input
7778 .insertAfter( this.$input
)
7779 .attr( 'aria-hidden', 'true' )
7780 .addClass( 'oo-ui-element-hidden' );
7783 this.setValidation( config
.validate
);
7784 this.setLabelPosition( config
.labelPosition
);
7788 keypress
: this.onKeyPress
.bind( this ),
7789 blur
: this.onBlur
.bind( this )
7792 focus
: this.onElementAttach
.bind( this )
7794 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
7795 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
7796 this.on( 'labelChange', this.updatePosition
.bind( this ) );
7797 this.connect( this, {
7799 disable
: 'onDisable'
7804 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
7805 .append( this.$icon
, this.$indicator
);
7806 this.setReadOnly( !!config
.readOnly
);
7807 this.updateSearchIndicator();
7808 if ( config
.placeholder
) {
7809 this.$input
.attr( 'placeholder', config
.placeholder
);
7811 if ( config
.maxLength
!== undefined ) {
7812 this.$input
.attr( 'maxlength', config
.maxLength
);
7814 if ( config
.autofocus
) {
7815 this.$input
.attr( 'autofocus', 'autofocus' );
7817 if ( config
.required
) {
7818 this.$input
.attr( 'required', 'required' );
7819 this.$input
.attr( 'aria-required', 'true' );
7821 if ( config
.autocomplete
=== false ) {
7822 this.$input
.attr( 'autocomplete', 'off' );
7823 // Turning off autocompletion also disables "form caching" when the user navigates to a
7824 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
7826 beforeunload: function () {
7827 this.$input
.removeAttr( 'autocomplete' );
7829 pageshow: function () {
7830 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
7831 // whole page... it shouldn't hurt, though.
7832 this.$input
.attr( 'autocomplete', 'off' );
7836 if ( this.multiline
&& config
.rows
) {
7837 this.$input
.attr( 'rows', config
.rows
);
7839 if ( this.label
|| config
.autosize
) {
7840 this.installParentChangeDetector();
7846 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
7847 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
7848 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
7849 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
7850 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
7852 /* Static Properties */
7854 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
7859 /* Static Methods */
7864 OO
.ui
.TextInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
7865 var state
= OO
.ui
.TextInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
7866 if ( config
.multiline
) {
7867 state
.scrollTop
= config
.$input
.scrollTop();
7875 * An `enter` event is emitted when the user presses 'enter' inside the text box.
7877 * Not emitted if the input is multiline.
7883 * A `resize` event is emitted when autosize is set and the widget resizes
7891 * Handle icon mouse down events.
7894 * @param {jQuery.Event} e Mouse down event
7897 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
7898 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
7899 this.$input
[ 0 ].focus();
7905 * Handle indicator mouse down events.
7908 * @param {jQuery.Event} e Mouse down event
7911 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
7912 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
7913 if ( this.type
=== 'search' ) {
7914 // Clear the text field
7915 this.setValue( '' );
7917 this.$input
[ 0 ].focus();
7923 * Handle key press events.
7926 * @param {jQuery.Event} e Key press event
7927 * @fires enter If enter key is pressed and input is not multiline
7929 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
7930 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
7931 this.emit( 'enter', e
);
7936 * Handle blur events.
7939 * @param {jQuery.Event} e Blur event
7941 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
7942 this.setValidityFlag();
7946 * Handle element attach events.
7949 * @param {jQuery.Event} e Element attach event
7951 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
7952 // Any previously calculated size is now probably invalid if we reattached elsewhere
7953 this.valCache
= null;
7955 this.positionLabel();
7959 * Handle change events.
7961 * @param {string} value
7964 OO
.ui
.TextInputWidget
.prototype.onChange = function () {
7965 this.updateSearchIndicator();
7966 this.setValidityFlag();
7971 * Handle disable events.
7973 * @param {boolean} disabled Element is disabled
7976 OO
.ui
.TextInputWidget
.prototype.onDisable = function () {
7977 this.updateSearchIndicator();
7981 * Check if the input is {@link #readOnly read-only}.
7985 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
7986 return this.readOnly
;
7990 * Set the {@link #readOnly read-only} state of the input.
7992 * @param {boolean} state Make input read-only
7995 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
7996 this.readOnly
= !!state
;
7997 this.$input
.prop( 'readOnly', this.readOnly
);
7998 this.updateSearchIndicator();
8003 * Support function for making #onElementAttach work across browsers.
8005 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
8006 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
8008 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
8009 * first time that the element gets attached to the documented.
8011 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
8012 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
8013 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
8016 if ( MutationObserver
) {
8017 // The new way. If only it wasn't so ugly.
8019 if ( this.$element
.closest( 'html' ).length
) {
8020 // Widget is attached already, do nothing. This breaks the functionality of this function when
8021 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
8022 // would require observation of the whole document, which would hurt performance of other,
8023 // more important code.
8027 // Find topmost node in the tree
8028 topmostNode
= this.$element
[ 0 ];
8029 while ( topmostNode
.parentNode
) {
8030 topmostNode
= topmostNode
.parentNode
;
8033 // We have no way to detect the $element being attached somewhere without observing the entire
8034 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
8035 // parent node of $element, and instead detect when $element is removed from it (and thus
8036 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
8037 // doesn't get attached, we end up back here and create the parent.
8039 mutationObserver
= new MutationObserver( function ( mutations
) {
8040 var i
, j
, removedNodes
;
8041 for ( i
= 0; i
< mutations
.length
; i
++ ) {
8042 removedNodes
= mutations
[ i
].removedNodes
;
8043 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
8044 if ( removedNodes
[ j
] === topmostNode
) {
8045 setTimeout( onRemove
, 0 );
8052 onRemove = function () {
8053 // If the node was attached somewhere else, report it
8054 if ( widget
.$element
.closest( 'html' ).length
) {
8055 widget
.onElementAttach();
8057 mutationObserver
.disconnect();
8058 widget
.installParentChangeDetector();
8061 // Create a fake parent and observe it
8062 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
8063 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
8065 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
8066 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
8067 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
8072 * Automatically adjust the size of the text input.
8074 * This only affects #multiline inputs that are {@link #autosize autosized}.
8079 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
8080 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
,
8081 idealHeight
, newHeight
, scrollWidth
, property
;
8083 if ( this.multiline
&& this.$input
.val() !== this.valCache
) {
8084 if ( this.autosize
) {
8086 .val( this.$input
.val() )
8087 .attr( 'rows', this.minRows
)
8088 // Set inline height property to 0 to measure scroll height
8089 .css( 'height', 0 );
8091 this.$clone
.removeClass( 'oo-ui-element-hidden' );
8093 this.valCache
= this.$input
.val();
8095 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
8097 // Remove inline height property to measure natural heights
8098 this.$clone
.css( 'height', '' );
8099 innerHeight
= this.$clone
.innerHeight();
8100 outerHeight
= this.$clone
.outerHeight();
8102 // Measure max rows height
8104 .attr( 'rows', this.maxRows
)
8105 .css( 'height', 'auto' )
8107 maxInnerHeight
= this.$clone
.innerHeight();
8109 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
8110 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
8111 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
8112 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
8114 this.$clone
.addClass( 'oo-ui-element-hidden' );
8116 // Only apply inline height when expansion beyond natural height is needed
8117 // Use the difference between the inner and outer height as a buffer
8118 newHeight
= idealHeight
> innerHeight
? idealHeight
+ ( outerHeight
- innerHeight
) : '';
8119 if ( newHeight
!== this.styleHeight
) {
8120 this.$input
.css( 'height', newHeight
);
8121 this.styleHeight
= newHeight
;
8122 this.emit( 'resize' );
8125 scrollWidth
= this.$input
[ 0 ].offsetWidth
- this.$input
[ 0 ].clientWidth
;
8126 if ( scrollWidth
!== this.scrollWidth
) {
8127 property
= this.$element
.css( 'direction' ) === 'rtl' ? 'left' : 'right';
8129 this.$label
.css( { right
: '', left
: '' } );
8130 this.$indicator
.css( { right
: '', left
: '' } );
8132 if ( scrollWidth
) {
8133 this.$indicator
.css( property
, scrollWidth
);
8134 if ( this.labelPosition
=== 'after' ) {
8135 this.$label
.css( property
, scrollWidth
);
8139 this.scrollWidth
= scrollWidth
;
8140 this.positionLabel();
8150 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
8151 return config
.multiline
?
8153 $( '<input>' ).attr( 'type', this.getSaneType( config
) );
8157 * Get sanitized value for 'type' for given config.
8159 * @param {Object} config Configuration options
8160 * @return {string|null}
8163 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
8164 var type
= [ 'text', 'password', 'search', 'email', 'url', 'date' ].indexOf( config
.type
) !== -1 ?
8167 return config
.multiline
? 'multiline' : type
;
8171 * Check if the input supports multiple lines.
8175 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
8176 return !!this.multiline
;
8180 * Check if the input automatically adjusts its size.
8184 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
8185 return !!this.autosize
;
8189 * Focus the input and select a specified range within the text.
8191 * @param {number} from Select from offset
8192 * @param {number} [to] Select to offset, defaults to from
8195 OO
.ui
.TextInputWidget
.prototype.selectRange = function ( from, to
) {
8196 var isBackwards
, start
, end
,
8197 input
= this.$input
[ 0 ];
8201 isBackwards
= to
< from;
8202 start
= isBackwards
? to
: from;
8203 end
= isBackwards
? from : to
;
8208 input
.setSelectionRange( start
, end
, isBackwards
? 'backward' : 'forward' );
8210 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
8211 // Rather than expensively check if the input is attached every time, just check
8212 // if it was the cause of an error being thrown. If not, rethrow the error.
8213 if ( this.getElementDocument().body
.contains( input
) ) {
8221 * Get an object describing the current selection range in a directional manner
8223 * @return {Object} Object containing 'from' and 'to' offsets
8225 OO
.ui
.TextInputWidget
.prototype.getRange = function () {
8226 var input
= this.$input
[ 0 ],
8227 start
= input
.selectionStart
,
8228 end
= input
.selectionEnd
,
8229 isBackwards
= input
.selectionDirection
=== 'backward';
8232 from: isBackwards
? end
: start
,
8233 to
: isBackwards
? start
: end
8238 * Get the length of the text input value.
8240 * This could differ from the length of #getValue if the
8241 * value gets filtered
8243 * @return {number} Input length
8245 OO
.ui
.TextInputWidget
.prototype.getInputLength = function () {
8246 return this.$input
[ 0 ].value
.length
;
8250 * Focus the input and select the entire text.
8254 OO
.ui
.TextInputWidget
.prototype.select = function () {
8255 return this.selectRange( 0, this.getInputLength() );
8259 * Focus the input and move the cursor to the start.
8263 OO
.ui
.TextInputWidget
.prototype.moveCursorToStart = function () {
8264 return this.selectRange( 0 );
8268 * Focus the input and move the cursor to the end.
8272 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
8273 return this.selectRange( this.getInputLength() );
8277 * Insert new content into the input.
8279 * @param {string} content Content to be inserted
8282 OO
.ui
.TextInputWidget
.prototype.insertContent = function ( content
) {
8284 range
= this.getRange(),
8285 value
= this.getValue();
8287 start
= Math
.min( range
.from, range
.to
);
8288 end
= Math
.max( range
.from, range
.to
);
8290 this.setValue( value
.slice( 0, start
) + content
+ value
.slice( end
) );
8291 this.selectRange( start
+ content
.length
);
8296 * Insert new content either side of a selection.
8298 * @param {string} pre Content to be inserted before the selection
8299 * @param {string} post Content to be inserted after the selection
8302 OO
.ui
.TextInputWidget
.prototype.encapsulateContent = function ( pre
, post
) {
8304 range
= this.getRange(),
8305 offset
= pre
.length
;
8307 start
= Math
.min( range
.from, range
.to
);
8308 end
= Math
.max( range
.from, range
.to
);
8310 this.selectRange( start
).insertContent( pre
);
8311 this.selectRange( offset
+ end
).insertContent( post
);
8313 this.selectRange( offset
+ start
, offset
+ end
);
8318 * Set the validation pattern.
8320 * The validation pattern is either a regular expression, a function, or the symbolic name of a
8321 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
8322 * value must contain only numbers).
8324 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
8325 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
8327 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
8328 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
8329 this.validate
= validate
;
8331 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
8336 * Sets the 'invalid' flag appropriately.
8338 * @param {boolean} [isValid] Optionally override validation result
8340 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
8342 setFlag = function ( valid
) {
8344 widget
.$input
.attr( 'aria-invalid', 'true' );
8346 widget
.$input
.removeAttr( 'aria-invalid' );
8348 widget
.setFlags( { invalid
: !valid
} );
8351 if ( isValid
!== undefined ) {
8354 this.getValidity().then( function () {
8363 * Check if a value is valid.
8365 * This method returns a promise that resolves with a boolean `true` if the current value is
8366 * considered valid according to the supplied {@link #validate validation pattern}.
8368 * @deprecated since v0.12.3
8369 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
8371 OO
.ui
.TextInputWidget
.prototype.isValid = function () {
8374 if ( this.validate
instanceof Function
) {
8375 result
= this.validate( this.getValue() );
8376 if ( result
&& $.isFunction( result
.promise
) ) {
8377 return result
.promise();
8379 return $.Deferred().resolve( !!result
).promise();
8382 return $.Deferred().resolve( !!this.getValue().match( this.validate
) ).promise();
8387 * Get the validity of current value.
8389 * This method returns a promise that resolves if the value is valid and rejects if
8390 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
8392 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
8394 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
8397 function rejectOrResolve( valid
) {
8399 return $.Deferred().resolve().promise();
8401 return $.Deferred().reject().promise();
8405 if ( this.validate
instanceof Function
) {
8406 result
= this.validate( this.getValue() );
8407 if ( result
&& $.isFunction( result
.promise
) ) {
8408 return result
.promise().then( function ( valid
) {
8409 return rejectOrResolve( valid
);
8412 return rejectOrResolve( result
);
8415 return rejectOrResolve( this.getValue().match( this.validate
) );
8420 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
8422 * @param {string} labelPosition Label position, 'before' or 'after'
8425 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
8426 this.labelPosition
= labelPosition
;
8428 // If there is no label and we only change the position, #updatePosition is a no-op,
8429 // but it takes really a lot of work to do nothing.
8430 this.updatePosition();
8436 * Update the position of the inline label.
8438 * This method is called by #setLabelPosition, and can also be called on its own if
8439 * something causes the label to be mispositioned.
8443 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
8444 var after
= this.labelPosition
=== 'after';
8447 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
8448 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
8450 this.valCache
= null;
8451 this.scrollWidth
= null;
8453 this.positionLabel();
8459 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
8460 * already empty or when it's not editable.
8462 OO
.ui
.TextInputWidget
.prototype.updateSearchIndicator = function () {
8463 if ( this.type
=== 'search' ) {
8464 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
8465 this.setIndicator( null );
8467 this.setIndicator( 'clear' );
8473 * Position the label by setting the correct padding on the input.
8478 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
8479 var after
, rtl
, property
;
8482 // Clear old values if present
8484 'padding-right': '',
8489 this.$element
.append( this.$label
);
8491 this.$label
.detach();
8495 after
= this.labelPosition
=== 'after';
8496 rtl
= this.$element
.css( 'direction' ) === 'rtl';
8497 property
= after
=== rtl
? 'padding-left' : 'padding-right';
8499 this.$input
.css( property
, this.$label
.outerWidth( true ) + ( after
? this.scrollWidth
: 0 ) );
8507 OO
.ui
.TextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
8508 OO
.ui
.TextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
8509 if ( state
.scrollTop
!== undefined ) {
8510 this.$input
.scrollTop( state
.scrollTop
);
8515 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
8516 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
8517 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
8519 * - by typing a value in the text input field. If the value exactly matches the value of a menu
8520 * option, that option will appear to be selected.
8521 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
8524 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
8526 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
8529 * // Example: A ComboBoxInputWidget.
8530 * var comboBox = new OO.ui.ComboBoxInputWidget( {
8531 * label: 'ComboBoxInputWidget',
8532 * value: 'Option 1',
8535 * new OO.ui.MenuOptionWidget( {
8537 * label: 'Option One'
8539 * new OO.ui.MenuOptionWidget( {
8541 * label: 'Option Two'
8543 * new OO.ui.MenuOptionWidget( {
8545 * label: 'Option Three'
8547 * new OO.ui.MenuOptionWidget( {
8549 * label: 'Option Four'
8551 * new OO.ui.MenuOptionWidget( {
8553 * label: 'Option Five'
8558 * $( 'body' ).append( comboBox.$element );
8560 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
8563 * @extends OO.ui.TextInputWidget
8566 * @param {Object} [config] Configuration options
8567 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
8568 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
8569 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
8570 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
8571 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
8573 OO
.ui
.ComboBoxInputWidget
= function OoUiComboBoxInputWidget( config
) {
8574 // Configuration initialization
8575 config
= $.extend( {
8578 // For backwards-compatibility with ComboBoxWidget config
8579 $.extend( config
, config
.input
);
8581 // Parent constructor
8582 OO
.ui
.ComboBoxInputWidget
.parent
.call( this, config
);
8585 this.$overlay
= config
.$overlay
|| this.$element
;
8586 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
8590 $container
: this.$element
,
8591 disabled
: this.isDisabled()
8595 // For backwards-compatibility with ComboBoxWidget
8599 this.$indicator
.on( {
8600 click
: this.onIndicatorClick
.bind( this ),
8601 keypress
: this.onIndicatorKeyPress
.bind( this )
8603 this.connect( this, {
8604 change
: 'onInputChange',
8605 enter
: 'onInputEnter'
8607 this.menu
.connect( this, {
8608 choose
: 'onMenuChoose',
8609 add
: 'onMenuItemsChange',
8610 remove
: 'onMenuItemsChange'
8616 'aria-autocomplete': 'list'
8618 // Do not override options set via config.menu.items
8619 if ( config
.options
!== undefined ) {
8620 this.setOptions( config
.options
);
8622 // Extra class for backwards-compatibility with ComboBoxWidget
8623 this.$element
.addClass( 'oo-ui-comboBoxInputWidget oo-ui-comboBoxWidget' );
8624 this.$overlay
.append( this.menu
.$element
);
8625 this.onMenuItemsChange();
8630 OO
.inheritClass( OO
.ui
.ComboBoxInputWidget
, OO
.ui
.TextInputWidget
);
8635 * Get the combobox's menu.
8637 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
8639 OO
.ui
.ComboBoxInputWidget
.prototype.getMenu = function () {
8644 * Get the combobox's text input widget.
8646 * @return {OO.ui.TextInputWidget} Text input widget
8648 OO
.ui
.ComboBoxInputWidget
.prototype.getInput = function () {
8653 * Handle input change events.
8656 * @param {string} value New value
8658 OO
.ui
.ComboBoxInputWidget
.prototype.onInputChange = function ( value
) {
8659 var match
= this.menu
.getItemFromData( value
);
8661 this.menu
.selectItem( match
);
8662 if ( this.menu
.getHighlightedItem() ) {
8663 this.menu
.highlightItem( match
);
8666 if ( !this.isDisabled() ) {
8667 this.menu
.toggle( true );
8672 * Handle mouse click events.
8675 * @param {jQuery.Event} e Mouse click event
8677 OO
.ui
.ComboBoxInputWidget
.prototype.onIndicatorClick = function ( e
) {
8678 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
8680 this.$input
[ 0 ].focus();
8686 * Handle key press events.
8689 * @param {jQuery.Event} e Key press event
8691 OO
.ui
.ComboBoxInputWidget
.prototype.onIndicatorKeyPress = function ( e
) {
8692 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
8694 this.$input
[ 0 ].focus();
8700 * Handle input enter events.
8704 OO
.ui
.ComboBoxInputWidget
.prototype.onInputEnter = function () {
8705 if ( !this.isDisabled() ) {
8706 this.menu
.toggle( false );
8711 * Handle menu choose events.
8714 * @param {OO.ui.OptionWidget} item Chosen item
8716 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuChoose = function ( item
) {
8717 this.setValue( item
.getData() );
8721 * Handle menu item change events.
8725 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuItemsChange = function () {
8726 var match
= this.menu
.getItemFromData( this.getValue() );
8727 this.menu
.selectItem( match
);
8728 if ( this.menu
.getHighlightedItem() ) {
8729 this.menu
.highlightItem( match
);
8731 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu
.isEmpty() );
8737 OO
.ui
.ComboBoxInputWidget
.prototype.setDisabled = function ( disabled
) {
8739 OO
.ui
.ComboBoxInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
8742 this.menu
.setDisabled( this.isDisabled() );
8749 * Set the options available for this input.
8751 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
8754 OO
.ui
.ComboBoxInputWidget
.prototype.setOptions = function ( options
) {
8757 .addItems( options
.map( function ( opt
) {
8758 return new OO
.ui
.MenuOptionWidget( {
8760 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
8769 * @deprecated since 0.13.2; use OO.ui.ComboBoxInputWidget instead
8771 OO
.ui
.ComboBoxWidget
= OO
.ui
.ComboBoxInputWidget
;
8774 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
8775 * which is a widget that is specified by reference before any optional configuration settings.
8777 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
8779 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8780 * A left-alignment is used for forms with many fields.
8781 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8782 * A right-alignment is used for long but familiar forms which users tab through,
8783 * verifying the current field with a quick glance at the label.
8784 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8785 * that users fill out from top to bottom.
8786 * - **inline**: The label is placed after the field-widget and aligned to the left.
8787 * An inline-alignment is best used with checkboxes or radio buttons.
8789 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
8790 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
8792 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8795 * @extends OO.ui.Layout
8796 * @mixins OO.ui.mixin.LabelElement
8797 * @mixins OO.ui.mixin.TitledElement
8800 * @param {OO.ui.Widget} fieldWidget Field widget
8801 * @param {Object} [config] Configuration options
8802 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
8803 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
8804 * The array may contain strings or OO.ui.HtmlSnippet instances.
8805 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
8806 * The array may contain strings or OO.ui.HtmlSnippet instances.
8807 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
8808 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
8809 * For important messages, you are advised to use `notices`, as they are always shown.
8811 * @throws {Error} An error is thrown if no widget is specified
8813 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
8814 var hasInputWidget
, div
;
8816 // Allow passing positional parameters inside the config object
8817 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
8818 config
= fieldWidget
;
8819 fieldWidget
= config
.fieldWidget
;
8822 // Make sure we have required constructor arguments
8823 if ( fieldWidget
=== undefined ) {
8824 throw new Error( 'Widget not found' );
8827 hasInputWidget
= fieldWidget
.constructor.static.supportsSimpleLabel
;
8829 // Configuration initialization
8830 config
= $.extend( { align
: 'left' }, config
);
8832 // Parent constructor
8833 OO
.ui
.FieldLayout
.parent
.call( this, config
);
8835 // Mixin constructors
8836 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8837 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
8840 this.fieldWidget
= fieldWidget
;
8843 this.$field
= $( '<div>' );
8844 this.$messages
= $( '<ul>' );
8845 this.$body
= $( '<' + ( hasInputWidget
? 'label' : 'div' ) + '>' );
8847 if ( config
.help
) {
8848 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
8849 classes
: [ 'oo-ui-fieldLayout-help' ],
8855 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
8856 div
.html( config
.help
.toString() );
8858 div
.text( config
.help
);
8860 this.popupButtonWidget
.getPopup().$body
.append(
8861 div
.addClass( 'oo-ui-fieldLayout-help-content' )
8863 this.$help
= this.popupButtonWidget
.$element
;
8865 this.$help
= $( [] );
8869 if ( hasInputWidget
) {
8870 this.$label
.on( 'click', this.onLabelClick
.bind( this ) );
8872 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
8876 .addClass( 'oo-ui-fieldLayout' )
8877 .append( this.$help
, this.$body
);
8878 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
8879 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
8881 .addClass( 'oo-ui-fieldLayout-field' )
8882 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget
.isDisabled() )
8883 .append( this.fieldWidget
.$element
);
8885 this.setErrors( config
.errors
|| [] );
8886 this.setNotices( config
.notices
|| [] );
8887 this.setAlignment( config
.align
);
8892 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
8893 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
8894 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
8899 * Handle field disable events.
8902 * @param {boolean} value Field is disabled
8904 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
8905 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
8909 * Handle label mouse click events.
8912 * @param {jQuery.Event} e Mouse click event
8914 OO
.ui
.FieldLayout
.prototype.onLabelClick = function () {
8915 this.fieldWidget
.simulateLabelClick();
8920 * Get the widget contained by the field.
8922 * @return {OO.ui.Widget} Field widget
8924 OO
.ui
.FieldLayout
.prototype.getField = function () {
8925 return this.fieldWidget
;
8930 * @param {string} kind 'error' or 'notice'
8931 * @param {string|OO.ui.HtmlSnippet} text
8934 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
8935 var $listItem
, $icon
, message
;
8936 $listItem
= $( '<li>' );
8937 if ( kind
=== 'error' ) {
8938 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
8939 } else if ( kind
=== 'notice' ) {
8940 $icon
= new OO
.ui
.IconWidget( { icon
: 'info' } ).$element
;
8944 message
= new OO
.ui
.LabelWidget( { label
: text
} );
8946 .append( $icon
, message
.$element
)
8947 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
8952 * Set the field alignment mode.
8955 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
8958 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
8959 if ( value
!== this.align
) {
8960 // Default to 'left'
8961 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
8965 if ( value
=== 'inline' ) {
8966 this.$body
.append( this.$field
, this.$label
);
8968 this.$body
.append( this.$label
, this.$field
);
8970 // Set classes. The following classes can be used here:
8971 // * oo-ui-fieldLayout-align-left
8972 // * oo-ui-fieldLayout-align-right
8973 // * oo-ui-fieldLayout-align-top
8974 // * oo-ui-fieldLayout-align-inline
8976 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
8978 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
8986 * Set the list of error messages.
8988 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
8989 * The array may contain strings or OO.ui.HtmlSnippet instances.
8992 OO
.ui
.FieldLayout
.prototype.setErrors = function ( errors
) {
8993 this.errors
= errors
.slice();
8994 this.updateMessages();
8999 * Set the list of notice messages.
9001 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
9002 * The array may contain strings or OO.ui.HtmlSnippet instances.
9005 OO
.ui
.FieldLayout
.prototype.setNotices = function ( notices
) {
9006 this.notices
= notices
.slice();
9007 this.updateMessages();
9012 * Update the rendering of error and notice messages.
9016 OO
.ui
.FieldLayout
.prototype.updateMessages = function () {
9018 this.$messages
.empty();
9020 if ( this.errors
.length
|| this.notices
.length
) {
9021 this.$body
.after( this.$messages
);
9023 this.$messages
.remove();
9027 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
9028 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
9030 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
9031 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
9036 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
9037 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
9038 * is required and is specified before any optional configuration settings.
9040 * Labels can be aligned in one of four ways:
9042 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9043 * A left-alignment is used for forms with many fields.
9044 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9045 * A right-alignment is used for long but familiar forms which users tab through,
9046 * verifying the current field with a quick glance at the label.
9047 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9048 * that users fill out from top to bottom.
9049 * - **inline**: The label is placed after the field-widget and aligned to the left.
9050 * An inline-alignment is best used with checkboxes or radio buttons.
9052 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
9053 * text is specified.
9056 * // Example of an ActionFieldLayout
9057 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
9058 * new OO.ui.TextInputWidget( {
9059 * placeholder: 'Field widget'
9061 * new OO.ui.ButtonWidget( {
9065 * label: 'An ActionFieldLayout. This label is aligned top',
9067 * help: 'This is help text'
9071 * $( 'body' ).append( actionFieldLayout.$element );
9074 * @extends OO.ui.FieldLayout
9077 * @param {OO.ui.Widget} fieldWidget Field widget
9078 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
9080 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
9081 // Allow passing positional parameters inside the config object
9082 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
9083 config
= fieldWidget
;
9084 fieldWidget
= config
.fieldWidget
;
9085 buttonWidget
= config
.buttonWidget
;
9088 // Parent constructor
9089 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
9092 this.buttonWidget
= buttonWidget
;
9093 this.$button
= $( '<div>' );
9094 this.$input
= $( '<div>' );
9098 .addClass( 'oo-ui-actionFieldLayout' );
9100 .addClass( 'oo-ui-actionFieldLayout-button' )
9101 .append( this.buttonWidget
.$element
);
9103 .addClass( 'oo-ui-actionFieldLayout-input' )
9104 .append( this.fieldWidget
.$element
);
9106 .append( this.$input
, this.$button
);
9111 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
9114 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
9115 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
9116 * configured with a label as well. For more information and examples,
9117 * please see the [OOjs UI documentation on MediaWiki][1].
9120 * // Example of a fieldset layout
9121 * var input1 = new OO.ui.TextInputWidget( {
9122 * placeholder: 'A text input field'
9125 * var input2 = new OO.ui.TextInputWidget( {
9126 * placeholder: 'A text input field'
9129 * var fieldset = new OO.ui.FieldsetLayout( {
9130 * label: 'Example of a fieldset layout'
9133 * fieldset.addItems( [
9134 * new OO.ui.FieldLayout( input1, {
9135 * label: 'Field One'
9137 * new OO.ui.FieldLayout( input2, {
9138 * label: 'Field Two'
9141 * $( 'body' ).append( fieldset.$element );
9143 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9146 * @extends OO.ui.Layout
9147 * @mixins OO.ui.mixin.IconElement
9148 * @mixins OO.ui.mixin.LabelElement
9149 * @mixins OO.ui.mixin.GroupElement
9152 * @param {Object} [config] Configuration options
9153 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
9155 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
9156 // Configuration initialization
9157 config
= config
|| {};
9159 // Parent constructor
9160 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
9162 // Mixin constructors
9163 OO
.ui
.mixin
.IconElement
.call( this, config
);
9164 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9165 OO
.ui
.mixin
.GroupElement
.call( this, config
);
9167 if ( config
.help
) {
9168 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
9169 classes
: [ 'oo-ui-fieldsetLayout-help' ],
9174 this.popupButtonWidget
.getPopup().$body
.append(
9176 .text( config
.help
)
9177 .addClass( 'oo-ui-fieldsetLayout-help-content' )
9179 this.$help
= this.popupButtonWidget
.$element
;
9181 this.$help
= $( [] );
9186 .addClass( 'oo-ui-fieldsetLayout' )
9187 .prepend( this.$help
, this.$icon
, this.$label
, this.$group
);
9188 if ( Array
.isArray( config
.items
) ) {
9189 this.addItems( config
.items
);
9195 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
9196 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
9197 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
9198 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
9201 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
9202 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
9203 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
9204 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9206 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
9207 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
9208 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
9209 * some fancier controls. Some controls have both regular and InputWidget variants, for example
9210 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
9211 * often have simplified APIs to match the capabilities of HTML forms.
9212 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
9214 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
9215 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9218 * // Example of a form layout that wraps a fieldset layout
9219 * var input1 = new OO.ui.TextInputWidget( {
9220 * placeholder: 'Username'
9222 * var input2 = new OO.ui.TextInputWidget( {
9223 * placeholder: 'Password',
9226 * var submit = new OO.ui.ButtonInputWidget( {
9230 * var fieldset = new OO.ui.FieldsetLayout( {
9231 * label: 'A form layout'
9233 * fieldset.addItems( [
9234 * new OO.ui.FieldLayout( input1, {
9235 * label: 'Username',
9238 * new OO.ui.FieldLayout( input2, {
9239 * label: 'Password',
9242 * new OO.ui.FieldLayout( submit )
9244 * var form = new OO.ui.FormLayout( {
9245 * items: [ fieldset ],
9246 * action: '/api/formhandler',
9249 * $( 'body' ).append( form.$element );
9252 * @extends OO.ui.Layout
9253 * @mixins OO.ui.mixin.GroupElement
9256 * @param {Object} [config] Configuration options
9257 * @cfg {string} [method] HTML form `method` attribute
9258 * @cfg {string} [action] HTML form `action` attribute
9259 * @cfg {string} [enctype] HTML form `enctype` attribute
9260 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
9262 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
9265 // Configuration initialization
9266 config
= config
|| {};
9268 // Parent constructor
9269 OO
.ui
.FormLayout
.parent
.call( this, config
);
9271 // Mixin constructors
9272 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
9275 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
9277 // Make sure the action is safe
9278 action
= config
.action
;
9279 if ( action
!== undefined && !OO
.ui
.isSafeUrl( action
) ) {
9280 action
= './' + action
;
9285 .addClass( 'oo-ui-formLayout' )
9287 method
: config
.method
,
9289 enctype
: config
.enctype
9291 if ( Array
.isArray( config
.items
) ) {
9292 this.addItems( config
.items
);
9298 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
9299 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
9304 * A 'submit' event is emitted when the form is submitted.
9309 /* Static Properties */
9311 OO
.ui
.FormLayout
.static.tagName
= 'form';
9316 * Handle form submit events.
9319 * @param {jQuery.Event} e Submit event
9322 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
9323 if ( this.emit( 'submit' ) ) {
9329 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
9330 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
9333 * // Example of a panel layout
9334 * var panel = new OO.ui.PanelLayout( {
9338 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
9340 * $( 'body' ).append( panel.$element );
9343 * @extends OO.ui.Layout
9346 * @param {Object} [config] Configuration options
9347 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
9348 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
9349 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
9350 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
9352 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
9353 // Configuration initialization
9354 config
= $.extend( {
9361 // Parent constructor
9362 OO
.ui
.PanelLayout
.parent
.call( this, config
);
9365 this.$element
.addClass( 'oo-ui-panelLayout' );
9366 if ( config
.scrollable
) {
9367 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
9369 if ( config
.padded
) {
9370 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
9372 if ( config
.expanded
) {
9373 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
9375 if ( config
.framed
) {
9376 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
9382 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
9387 * Focus the panel layout
9389 * The default implementation just focuses the first focusable element in the panel
9391 OO
.ui
.PanelLayout
.prototype.focus = function () {
9392 OO
.ui
.findFocusable( this.$element
).focus();
9396 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
9397 * items), with small margins between them. Convenient when you need to put a number of block-level
9398 * widgets on a single line next to each other.
9400 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
9403 * // HorizontalLayout with a text input and a label
9404 * var layout = new OO.ui.HorizontalLayout( {
9406 * new OO.ui.LabelWidget( { label: 'Label' } ),
9407 * new OO.ui.TextInputWidget( { value: 'Text' } )
9410 * $( 'body' ).append( layout.$element );
9413 * @extends OO.ui.Layout
9414 * @mixins OO.ui.mixin.GroupElement
9417 * @param {Object} [config] Configuration options
9418 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
9420 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
9421 // Configuration initialization
9422 config
= config
|| {};
9424 // Parent constructor
9425 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
9427 // Mixin constructors
9428 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
9431 this.$element
.addClass( 'oo-ui-horizontalLayout' );
9432 if ( Array
.isArray( config
.items
) ) {
9433 this.addItems( config
.items
);
9439 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
9440 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);